简单而While Loop卡在Python 3.3中

时间:2014-02-07 17:23:53

标签: python-3.x while-loop

每次我运行这段代码时,Python IDLE都会在屏幕上开始发送1和2的垃圾邮件。我正在使用Python 3.3,所以我可能会遗漏一些内容:

count=1

然后作为单独的条目:

while count<=5:
print count
count+1

我正在阅读的书略显过时,所以我意识到打印是一种功能,正确的写作方式是:

print(count)

但除此之外,我被困住了,并且它一直在发送垃圾邮件1和2。它的意思是从1到5自动计数。虽然我在这里,但我应该从2.7到3.3知道多少其他更新?

2 个答案:

答案 0 :(得分:2)

您没有更改count的值,为此,您应该将count + 1的结果分配给它:

count = count + 1

甚至更简单:

count += 1

答案 1 :(得分:0)

正如克里斯蒂安所说,只需将count=1替换为count= count+1count+=1。 while循环继续,直到它的条件为false。 count + 1只计算一个新计数;它实际上并没有存储它。一个工作的例子:

count= 1
while count<=5:
    print(count)
    count= count+1 #calculates a new count AND stores it

这会产生预期的输出:

1
2
3
4
5

另外,您可能需要注意在一个位置开始计数,并使用<=运算符来停止计数。 Python和大多数其他语言倾向于从0开始计数,然后在<运算符的'limit'之前结束它。一个小字符串示例,说明用'0'引用的'first'字符而不是更明显的'1':

word= 'spam'
print(word[0]) #the first character
print(word[3]) #the second character
print(word[4]) #not in the string. Produces error.

结果是:

's'
'm'
IndexError:string index out of range

以下代码执行相同的操作,并且与其他python语法更加一致:

count= 0
while count < 5:
    count= count+1
    print(count)

或者如果你想在最后增加计数:

count= 0
while count < 5:
    print(count+1)
    count= count+1

这两种方式中的任何一种都使用更传统的开始计数的路径为n为0并递增到n-1。起初看起来可能更令人困惑,但它会在以后得到回报。祝好运!我希望当你真正需要的只是一行时,我不只是深入研究不必要的细节:)

相关问题