简体   繁体   English

while循环不在python中退出

[英]While-loop not exiting in python

I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so. 我现在正在尝试自学python,而且我正在使用“学习Python艰难之路”这样的练习。

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. 现在,我正在进行一个涉及while循环的练习,在那里我从脚本中获取while循环,将其转换为函数,然后在另一个脚本中调用该函数。 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)

I believe you want this. 我相信你想要这个。

count = int(raw_input("Enter number of cycles: "))

Without converting the input to integer, you end up with a string in the count variable, ie if you enter 1 when the program asks for input, what goes into count is '1' . 如果不将输入转换为整数,则最终会在count变量中输入一个字符串,即如果在程序要求输入时输入1 ,则计数为'1'

A comparison between string and integer turns out to be False . 字符串和整数之间的比较结果为False So the condition in while i < counter: is always False because i is an integer while counter is a string in your program. 因此, while i < counter:的条件总是为False因为i是一个整数,而counter是程序中的一个字符串。

In your program, you could have debugged this yourself if you had used print repr(count) instead to check what the value in count variable is. 在您的程序中,如果您使用了print repr(count)来检查count变量中的值是什么,那么您可以自己调试它。 For your program, it would show '1' when you enter 1. With the fix I have suggested, it would show just 1 . 对于你的程序,当你输入1时它会显示'1' 。根据我建议的修正,它只显示1

将输入字符串转换为整数... count=int(count)

Above has been cleared why the while looped for ever. 以上已被清除为什么同时循环永远。 It loops for a lot(=ASCII code which is really big) 它循环很多(= ASCII代码真的很大)

But to fix the while you can simply: 但要解决这个问题你可以简单地说:

while i<int(counter):
    print "At the top i is %d" % i
    numbers.append(i)

raw_input returns a string, but i is an integer. raw_input返回一个字符串,但i是一个整数。 Try using input instead of raw_input . 尝试使用input而不是raw_input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM