Python Loops: Extra Print?

我们两清 提交于 2020-01-04 06:34:16

问题


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! :)


回答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)



回答2:


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




回答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.



来源:https://stackoverflow.com/questions/14329176/python-loops-extra-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!