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
Run Code Online (Sandbox Code Playgroud)
所以我正在关注lpthw并且只是搞乱了代码,为什么当我使用raw_input并输入一个像6这样的数字时这个循环会变成无限循环?不应该i = i + 1在那里阻止这种情况发生吗?
在Python 2.7中,raw_input返回一个str(字符串).因此,当您进行比较时i < a,您将整数与字符串进行比较,它将始终返回True.
要解决此问题,请将输入转换为整数:
a = int(raw_input(...))
Run Code Online (Sandbox Code Playgroud)
注意:作为@AshwiniChaudhary评论,比较(与<,<=,>或>=的整数.)与在Python 3.x的字符串将引发一个例外:
TypeError: unorderable types: int() <operator> str()
Run Code Online (Sandbox Code Playgroud)