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!')
4
  • Sorry for the typo. I meant "figure out". Commented Mar 29, 2020 at 4:14
  • 1
    The guess you are reading from the user is a string. The num you are getting from the randint is an integer. You should covert the guess to an integer before comparing, like this: if int(guess) == num: ... Commented Mar 29, 2020 at 4:19
  • It works perfectly! Thank you. Commented Mar 29, 2020 at 4:20
  • 1
    mark it as "solved" by clicking the "tick" near the answer.Welcome to stackoverflow! Commented Mar 29, 2020 at 4:21

1 Answer 1

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.

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

4 Comments

There have got to be a million duplicates for this question, but the SO search is failing me.
@KarlKnechtel - similar, but not an exact dupe - stackoverflow.com/questions/17661829/…
@KarlKnechtel there is also stackoverflow.com/questions/20449427/…
@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 - stackoverflow.com/questions/40403108/…

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.