Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: While loop will not terminate

I have read a lot of topics regarding while loops and I can't find one that tells me what I have done wrong with my own code. I am doing the Learn Python the Hard Way and I wrote this code in order to satisfy the study drill #1 for exercise 33. I cannot figure out why the loop won't terminate when I put in my raw data.

numbers = []

def number_uno(z):
    i = 0
    while i < z:
        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


print "Pick a random number: "
z = raw_input("> ")

number_uno(z)

print "Done"

Any ideas? it just keeps adding 1 to "i" and will not stop printing.

Thanks, Zach

like image 696
zkirkland Avatar asked Sep 03 '26 16:09

zkirkland


1 Answers

raw_input returns a string. when you pass it to your function, you're comparing an integer and a string. Note that this behavior was deprecated in python3.x. You can't compare integers with strings in python 3.x in this way. (It'll raise a TypeError).

You can remedy this quite easily:

number_uno(int(z))

should run OK.

like image 110
mgilson Avatar answered Sep 05 '26 05:09

mgilson