3

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

0

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I wonder why it's even allowed in Python2 and what the result means.
@LevLevitsky -- in python2, the ordering is determined by object type, but is implementation dependent. In other words 1 > "foo" will give the same result as 100 > "bar", but what that result actually is isn't well defined.
In CPython 2.x, the default behavior when comparing objects of different types is to compare their types as strings. Thus all integers are less than all strings, because "int" < "str". This was done to segregate the objects by type while sorting lists containing various types, but I don't believe other Python implementations are obliged to do the same.
Wow. I don't know what else to say :)
@kindall -- thanks for explaining the rational (and algorithm that cpython2.x uses). I always wondered how it decided since it's not mentioned in the docs
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.