Python循环:额外打印? [英] Python Loops: Extra Print?
问题描述
for i in [1 ,3,5,7,9]:
print(i,:,i ** 3)
print(i)
打印出来
$ $ $ $ $ $ $ $ $ 1 $ 1
3: 27
5:125
7:343
9:729
9
我的问题是为什么打印额外的9?最后一个循环打印是不是9:729?
必须与
print(i,:,i ** 3)
因为如果我只是放在: 它只是打印 先谢谢了,因为我没有人帮我! :) 所以,在你的情况下, 循环执行时,它将 一旦循环终止,它将继续执行下一行代码,这完全独立于for循环。所以,你在for循环之后有一个命令,它是 你想要的是: Im doing a back of the book exercise in Python Programming: An Intro to Comp Sci: this prints out 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 because if I just put in: It just prints Thanks in advance as I have nobody else to help me! :) In python for loops, the "body" of the loop is indented. So, in your case, As the loop executes, it changes the value of 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 What you want is:
这篇关于Python循环:额外打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$我在[1,3,5,7,9]:
print(i)
>
1
3
5
7
9
print(i,:,i ** 3)
是body。它将从1开始并结束,为 i
的每个值打印 i,:,i ** 3
i
的值更改为列表中的下一个项目。
print(i)
。由于 i
上次设置为9,所以此命令基本上意味着 print(9)
。
for i in [1,3,5,7,9 ]:
print(i,:,i ** 3)
for i in [1,3,5,7,9]:
print(i, ":", i**3)
print(i)
1:1
3:27
5:125
7:343
9:729
9
print(i, ":", i**3)
for i in [1,3,5,7,9]:
print(i)
1
3
5
7
9
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.i
to the next item in the list.print(i)
. Since i
was last set at 9, this command basically means print(9)
.for i in [1,3,5,7,9]:
print(i, ":", i**3)