Skip to content Skip to sidebar Skip to footer

Python Loops: Extra Print?

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

Solution 1:

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)

Solution 2:

the print(i) at the last line..............

Solution 3:

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.

Post a Comment for "Python Loops: Extra Print?"