Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 425
detroitwilly Avatar asked Jan 27 '26 12:01

detroitwilly


1 Answers

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, i.e. 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.

like image 173
Susam Pal Avatar answered Jan 29 '26 02:01

Susam Pal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!