1

This is my current code it prints two random numbers between 1 and 20 and asks the user to add them together. I want it to say correct when the answer has been answered correctly, but I am not to sure how to do this.

The program runs fine it will work but when the user enters the correct answer nothing happens.

from random import randint


def Add(x, y):

    return x + y


num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = input("What is the answer to the question: ")

if ("answer") is (num1 + num2):
    print("Correct")

3 Answers3

4

You need to cast input to an int, use the actual variable answer and don't use is to test equality, is should be used to check identity, and will fail for numbers > 256 in your case:

num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = int(input("What is the answer to the question: "))

if  answer ==  num1 + num2:
    print("Correct")

Why is should not be used:

In [35]: i = 256

In [36]: j = 256

In [37]:  i is j
Out[37]: True

In [38]: i = 257

In [39]: j = 257

In [40]:  i is j
Out[40]: False

The only reason i is j is True for 256 is because python caches small ints from -5 to 256.

Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

You put answer in quotations which means that the program is expecting the string "answer" instead of the variable.

0

I fixed your last line. I used your Add() function just because you defined it.

from random import randint


def Add(x, y):

    return x + y


num1 = randint(1,20)
num2 = randint(1,20)
print(num1, "+", num2)
answer = input("What is the answer to the question: ")

if int(answer) == Add(num1 , num2):
    print("Correct")
else:
    print("Incorrect")
Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30