a = raw_input ("enter a number")
i = 0
numbers = []
while i < a:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now:", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
所以我在关注 lpthw 并且只是搞乱了代码,为什么当我使用 raw_input 并输入像 6 这样的数字时这个循环变成了无限循环? i = i + 1 不应该在那里阻止这种情况发生吗?
请您参考如下方法:
在 Python 2.7 中,raw_input返回 str (字符串)。所以当你比较i < a ,你正在比较一个整数和一个字符串,它会 always return True .
要解决此问题,请将您的输入转换为整数:
a = int(raw_input(...))
注意:正如@AshwiniChaudhary 评论的那样,比较(与 < 、 <= 、 > 或 >= )整数与 Python 3.x 中的字符串将引发异常:
TypeError: unorderable types: int() <operator> str()
