0

I am trying to make a simple guessing game. When I run the code and print the number in advance to check if the program is working, it keeps on having the same wrong response. In other words, even if the guess variable is equal to the num variable, the program still returns "Incorrect!", and I can't figure out why. Thank you in advance. The code is pretty self-explanatory, so I'll post it here.

import random

num = random.randint(1, 6)
print(num)

guess = input(f'Guess a number: ')

if guess == num:
    print(f'Correct!')
else:
    print(f'Incorrect!')
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153

1 Answers1

3

You are comparing different types. num is an integer number while the guess is a string. You need to convert it to an integer before comparing them.

Try using num == int(guess) instead.

Locke
  • 7,626
  • 2
  • 21
  • 41
  • 2
    There have got to be a million duplicates for this question, but the SO search is failing me. – Karl Knechtel Mar 29 '20 at 04:21
  • @KarlKnechtel - similar, but not an exact dupe - https://stackoverflow.com/questions/17661829/how-to-compare-string-and-integer-in-python – Boris Lipschitz Mar 29 '20 at 04:22
  • @KarlKnechtel there is also https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers – Locke Mar 29 '20 at 04:24
  • @KarlKnechtel - this is also related, but asks "how it does that" not "why it doesn't work", although, i guess, the initial question in his head was the same - https://stackoverflow.com/questions/40403108/how-can-python-compare-strings-with-integers – Boris Lipschitz Mar 29 '20 at 04:24