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() Commented 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. Commented 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.

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

1 Comment

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 :)
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()

Comments

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!

Comments

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.