det*_*lly 3 python infinite-loop while-loop
我现在正在尝试自学python,而我正在使用"学习Python艰难之路"中的练习来完成这项工作.
现在,我正在进行涉及while循环的练习,在这里我从脚本中获取while循环,将其转换为函数,然后在另一个脚本中调用该函数.最终程序的唯一目的是将项添加到列表中,然后在列表中打印.
我的问题是,一旦我调用该函数,嵌入式循环决定无限继续.
我已经多次分析了我的代码(见下文),并且找不到任何明显的错误.
def append_numbers(counter):
i = 0
numbers = []
while i < counter:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
count = raw_input("Enter number of cycles: ")
print count
raw_input()
append_numbers(count)
Run Code Online (Sandbox Code Playgroud)
Sus*_*Pal 15
我相信你想要这个.
count = int(raw_input("Enter number of cycles: "))
Run Code Online (Sandbox Code Playgroud)
如果不将输入转换为整数,最后会在count变量中输入一个字符串,即如果1在程序要求输入时输入,则计入的内容为'1'.
字符串和整数之间的比较结果证明False.所以条件while i < counter:总是False因为i是一个整数而counter在你的程序中是一个字符串.
在你的程序中,你可以自己调试它,如果你曾经使用print repr(count)过来检查count变量中的值是什么.对于你的程序,它会'1'在你输入1时显示.通过我建议的修复,它会显示1.