我的代码没有停止。我希望有人可以解释我做错了什么。
我尝试做的是运行程序,给它一个数字并让它循环直到达到该数字。我给程序x,x给予计数。并且它应该每次检查i到x。
numbers = []
x = raw_input("> ")
def counting(num):
i = 0
while i < num:
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
counting(x)
print "The numbers: "
for num in numbers:
print num
答案 0 :(得分:3)
x = int(raw_input("> "))
,您正在将字符串与int进行比较。您还可以使用范围:
def counting(num):
for i in range(num):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % (i + 1)
如果您确实希望print "At the bottom i is %d" % i
仅打印最后一个i
,请将其移到循环外。:
def counting(num):
for i in range(num):
print "At the top i is {}".format(i)
numbers.append(i)
print "Numbers now: {}".format(numbers)
print "At the bottom i is {}".format(i)
答案 1 :(得分:1)
在Python 2中,raw_input()
返回一个字符串(如Python 3的input()
)。您将这个直接发送到您的计数功能。
同样在Python 2中,您可以比较字符串和整数,Python也不会抱怨。当您尝试使用其中一个时,这会给您带来意想不到的结果,这可能是比较字符串和整数时Python 3会引发错误的原因。