-2

This program is suppose to generate two random numbers and have the user input the result. If the user input is correct, then the program will print 'You are correct!' If wrong, the program will print 'You are wrong!' However, when the user's answer is correct, the program still outputs "You are wrong!' Not sure why

 import random
 first = random.randint(0,9) 
 second = random.randint(0,9) 
 result = first + second
 answer = input(str(first) + ' + ' + str(second) + ': ')

 if result == answer:
     print('You are correct!')
 else:
     print('Sorry you are wrong!')

1 Answers1

0

Because the result is an integer and the answer is a string.

You need to convert the result to a string before comparing:

if str(result) == answer:
ababak
  • 1,685
  • 1
  • 11
  • 23
  • This won't always work. – quamrana Oct 10 '19 at 14:59
  • Could you give an example when it doesn't? The spaces? – ababak Oct 10 '19 at 15:00
  • Sure: first=4 second=5 result=9, answer = " 9". Output is: 'Sorry you are wrong!' – quamrana Oct 10 '19 at 15:02
  • Okay, then `if result == int(answer):` will fail when the answer is 'nine' ;) The question was not about data validation so I didn't use `if str(result) == answer.strip()` – ababak Oct 10 '19 at 15:04
  • If answer='nine', then neither way will work. Why would the user enter 'nine' when asked '4 + 5:'. Also, the answers in the duplicate question usually involve `int()` somewhere. – quamrana Oct 10 '19 at 15:08
  • My point is that the `int()` version will crash while the `str()` version will say about the wrong answer ;) – ababak Oct 10 '19 at 15:40
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/200660/discussion-between-quamrana-and-ababak). – quamrana Oct 10 '19 at 15:41