python中的while循环不退出
我现在正在尝试自学 Python,并且正在使用“Learn Python The Hard Way”中的练习来做到这一点。
现在,我正在做一个涉及 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)
I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so.
Right now, I'm working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the final program is to add items to a list and then print the list as it goes.
My issue is that once I call the function, the embedded loop decides to continue infinitely.
I've analyzed my code (see below) a number of times, and can't find anything overtly wrong.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信你想要这个。
如果不将输入转换为整数,您最终会在
count
变量中得到一个字符串,即,如果您在程序要求输入时输入1
,则进入 count 的是 <代码>'1'。字符串和整数之间的比较结果为
False
。所以while i
中的条件counter:
始终为False
,因为在程序中,i
是整数,而counter
是字符串。在您的程序中,如果您使用
print repr(count)
来检查count
变量中的值,您可以自己调试它。对于您的程序,当您输入 1 时,它会显示'1'
。通过我建议的修复,它只会显示1
。I believe you want this.
Without converting the input to integer, you end up with a string in the
count
variable, i.e. if you enter1
when the program asks for input, what goes into count is'1'
.A comparison between string and integer turns out to be
False
. So the condition inwhile i < counter:
is alwaysFalse
becausei
is an integer whilecounter
is a string in your program.In your program, you could have debugged this yourself if you had used
print repr(count)
instead to check what the value incount
variable is. For your program, it would show'1'
when you enter 1. With the fix I have suggested, it would show just1
.将输入字符串转换为整数...
count=int(count)
convert the input string to integer...
count=int(count)
上面已经解释了为什么 while 永远循环。它循环了很多次(=ASCII 代码非常大)
但是要修复 while 你可以简单地:
Above has been cleared why the while looped for ever. It loops for a lot(=ASCII code which is really big)
But to fix the while you can simply:
raw_input
返回一个字符串,但i
是一个整数。尝试使用input
而不是raw_input
。raw_input
returns a string, buti
is an integer. Try usinginput
instead ofraw_input
.