简体   繁体   中英

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.

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)

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' .

A comparison between string and integer turns out to be False . So the condition in while i < counter: is always False because i is an integer while counter 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 in count variable is. For your program, it would show '1' when you enter 1. With the fix I have suggested, it would show just 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)

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. Try using input instead of raw_input .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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