0

I am writing a simple code to generate two random numbers from 1 to 10 and then the user would have to answer it. However, when I am comparing the correct answer of the question to the number user has inputted, they appear to be unequal. I printed the variable and it was exactly the same as what I had input. I am quite new to python and just wanted to make a little code to get familiar.

Code and output is listed below

Code:


answer = 0
num1 = random.randint(0,9)
num2 = random.randint(0,9)

result = num1 + num2
print(result)
print(num1, "+", num2)

answer = input("Answer: ")
if result == answer:
    print("Correct")
else:
    print("Incorrect")

input("Press ENTER to exit")

Output:

5
4 + 1
Answer: 5
Incorrect
Press ENTER to exit
TheEagle
  • 5,808
  • 3
  • 11
  • 39
Azure
  • 11
  • 1
    `sum` is a python function, it shouldn't be the name of a variable – Chris Jan 18 '21 at 16:21
  • `answer` is a string, `sum` is a number. See the difference with `print(repr(sum), repr(answer))`. – deceze Jan 18 '21 at 16:21
  • `input()` returns string. "1" is_not_ equal to 1. use `int(input())`. – fukanchik Jan 18 '21 at 16:22
  • I think that python `input` converts to string, so in the end you may be comparing a string with a int, which will away return false... – Yago Azedias Jan 18 '21 at 16:23
  • @Yago `input` doesn't "convert" to string, it simply *accepts* only strings. Anything and everything you *type* into your computer is by default and by definition a string, unless explicitly interpreted as and converted to some other more specific type. – deceze Jan 18 '21 at 16:26
  • As mentioned above, sum is a built in function. I would practice naming your variables to something more telling and relative to your task. Doing so will not only create more readable code, but will prevent similar instances from occurring. – MF- Jan 18 '21 at 16:28
  • @deceze it was not what the official python doc says `If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.` https://docs.python.org/3/library/functions.html#input – Yago Azedias Jan 18 '21 at 16:28
  • @Yago That is somewhat misleading without context. It converts it *from (external) binary input to a Python `str`.* It does not, say, accept a number as input and then goes out of its way to turn it into a string nonetheless. – deceze Jan 18 '21 at 16:30

0 Answers0