Reputation: 166
Im doing a back of the book exercise in Python Programming: An Intro to Comp Sci:
for i in [1,3,5,7,9]:
print(i, ":", i**3)
print(i)
this prints out
1:1
3:27
5:125
7:343
9:729
9
My questions is why does it print the extra 9? Wouldn't the last loop print be 9:729 ? It has to be something to do with the
print(i, ":", i**3)
because if I just put in:
for i in [1,3,5,7,9]:
print(i)
It just prints
1
3
5
7
9
Thanks in advance as I have nobody else to help me! :)
Upvotes: 2
Views: 185
Reputation: 7169
The last value assigned to i
is 9, so your last line referes to this value assignment that occurred within the loop. While 9:729
was the last thing printed, it was not the last assignment.
Edit:
why wouldn't it print something like this: 1:1 1 3:27 3 5:125 5 7:343 7 9:729 9?
It would print this if your code were indented and looked like this:
for i in [1,3,5,7,9]:
print(i, ":", i**3)
print(i)
The lack of indentation in the last line causes it to fall outside the for loop.
Upvotes: 1
Reputation: 6238
In python for loops, the "body" of the loop is indented.
So, in your case, print(i, ":", i**3)
is the "body". It will print i, ":", i**3
for each value of i
, starting at 1 and ending at 9.
As the loop executes, it changes the value of i
to the next item in the list.
Once the loop terminates, it continues to the next line of code, which is completely independent of the for-loop. So, you have a single command after the for-loop, which is print(i)
. Since i
was last set at 9, this command basically means print(9)
.
What you want is:
for i in [1,3,5,7,9]:
print(i, ":", i**3)
Upvotes: 3