Python循环:额外打印? [英] Python Loops: Extra Print?

查看:157
本文介绍了Python循环:额外打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  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) 

因为如果我只是放在:

<$我在[1,3,5,7,9]:
print(i)
>

它只是打印

  1 
3
5
7
9

先谢谢了,因为我没有人帮我! :)

解决方案

在python for循环中,循环的body被缩进。

所以,在你的情况下, print(i,:,i ** 3)是body。它将从1开始并结束,为 i 的每个值打印 i,:,i ** 3



循环执行时,它将 i 的值更改为列表中的下一个项目。

一旦循环终止,它将继续执行下一行代码,这完全独立于for循环。所以,你在for循环之后有一个命令,它是 print(i)。由于 i 上次设置为9,所以此命令基本上意味着 print(9)



你想要的是:

  for i in [1,3,5,7,9 ]:
print(i,:,i ** 3)


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

解决方案

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)

这篇关于Python循环:额外打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆