-3

I'm writing a simple program that compares two variables

from random import randint
result = (randint(1, 6))

guess = input('Guess the number: ')
if guess == result:
    print('You got it right')
else:
    print('Wrong')
    print(result)

The program sets the variable result as a random number, and then the user inputs a number that they guess. However, even when they get the number right, it says that they were wrong.

How can I get it so that when they get the correct number, it says that they are right?

Thanks in advance!

Giacomo
  • 156
  • 1
  • 16
  • 1
    change `guess=int(input(Guess the number : ')` – R.A.Munna Sep 26 '17 at 08:42
  • I have seen some similar questions which also have problem about variable comparing and a guess number game. Hum... so strange, why there are so many people want to make guess number game? – Sraw Sep 26 '17 at 08:43

3 Answers3

3

Here you are comparing an int to a string due to return type of input() being string. That will always give False.

Change your input guess to :

guess = int(input())

So,

IN : result = 5
IN : guess = 5
OUT : 'You got it right'
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
3

Either make INTEGER type to STRING or vice versa so that comparison can be done. Two different types (INT and STR) can not be compared.

e.g. code 01 [ both compared variables are string]

from random import randint
result = (randint(1, 6))

guess = input('Guess the number: ')
if guess == str(result):
    print('You got it right')
else:
    print('Wrong')
    print(result)

e.g. code 02 [ both compared variables are integer]

from random import randint
result = (randint(1, 6))

guess = input('Guess the number: ')
if int(guess) == result:
    print('You got it right')
else:
    print('Wrong')
    print(result)
Fuzed Mass
  • 414
  • 1
  • 3
  • 10
  • Awesome, thank you very much! Didn't remember you could do that, this worked perfectly. Thank you very much! – Giacomo Sep 26 '17 at 08:46
  • 1
    glad to hear that. you can further add error handling, because right now if user inputs a character instead of DIGIT the program will crash. – Fuzed Mass Sep 26 '17 at 08:47
0

change guess = input('Guess the number: ') to guess=int(input(Guess the number : ')

because input() take a string as a user input.

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29