Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:

   foo = 1
   guessfoo = input('Guess my number: ')
   if foo == guessfoo:
       print('Well done, You guessed it!')
   if foo != guessfoo:
       print('haha, fail.')

Why doesn't this work? And how should I be doing it? I am a beginner at this, please help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

With python version 3 :

input() returns a 'str' (string) object. A string compares to an integer returns False :

1 == '1'
False

You must cast your input like that :

guessfoo = int(input('Guess my number: '))

Don't forget to try...except if the result of the input cannot be casted into an int.

Full example code :

try:
    foo = 1
    guessfoo = int(input('Guess my number: '))
    if foo == guessfoo:
        print('Well done, You guessed it!')
    else:
        print('haha, fail.')
except ValueError:
    # cannot cast your input
    pass

EDIT:

With python version 2 :

Thanks for this comment :

In previous versions, input would eval the string, so if the user typed in 1, input returned an int.

Ouput or your original code:

$ python2 test.py 
Guess my number: 1
Well done, You guessed it!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...