2

I am a beginner in python. My program is to set a number (I am not using random.randint for the moment) and I try to guess it. So here is the code:

def game():
    print "I am thinking of a number between 1 and 10!"
    global  x
    x = 7
    y = raw_input("Guess!")
    while x > y:
        y = raw_input("Too low. Guess again!")
    while x < y:
        y = raw_input("Too high. Guess again!")
    if x == y:
        return "You got it! The number was" + x + " !"

but when I run this, the program states that x < y, no matter WHAT number I put in. Please, can someone help me? Thank you.

2
  • 1
    In python 3, you can no longer compare an int and a str >>> print(1 < '2') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str()
    – dstromberg
    Nov 1, 2013 at 18:26
  • thanks, but i am using python 2 not 3. think it's the same thing between str and int regardless of version.
    – Yubin Lee
    Dec 21, 2014 at 8:08

3 Answers 3

9

You need to convert y to an integer before comparing it to x:

y = int(raw_input("Guess!"))

Otherwise, you are comparing variables of different types, and the result is not always intuitive (such as x always being less than y). You can apply the same approach for the other times you ask the user to input y.

1
  • Well at least convert them to be the same type. Since the user might be a smart aleck and put an irrational number in between 1 and 10 :)
    – JonathanV
    Nov 1, 2013 at 18:35
4

You may want this:

def game():
    print "I am thinking of a number between 1 and 10!"
    global  x
    x = 7
    while True:
        y = int(raw_input("Guess! ")) # Casting the string input to int
        if x > y:
            y = raw_input("Too low. Guess again!")
        elif x < y:
            y = raw_input("Too high. Guess again!")
        elif x == y:
            print "You got it! The number was " + str(x) + " !"
            break # To exit while loop

game()
1

Y has to be an integer like x. A simple way to do this is:

y=int(raw_input("etc."))

You cannot compare two different variable types in python! Hope this helps!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.