Why does my math program say that I'm wrong?

Advertisements

So, I’m trying to make a math problem in Python, since I’m a beginner learning how to code. Basically, it asks you how many questions you want to answer, and to answer questions of addition, subtraction, multiplication, and division correctly. But whenever I try to answer the questions correctly, they always say that I’m incorrect. Let me show you the code I have, so far.

import random

num_question = (int)(input("Enter how many questions would you like to solve: "))
num1 = random.randint (0,20)
num2 = random.randint (0,20)
oper = ["+","-","*","/"]
operator = random.choice(oper) #chooses a variable in the "oper" list at random. Then it is used in the question

for count in range (0, num_question):
    question = ("What is " + str(num1) + " " + operator + " " + str(num2) + "?") #e.g. What is 6 - 2
    print (question)
    answer = (int)(input("Enter here: "))
    if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
        answer == (num1 + num2)
    elif operator == "-":
        answer == (num1 - num2)
    elif operator == "*":
        answer == (num1 * num2)
    elif operator == "/":
        answer == (num1 / num2)
    
    if question == answer: #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
        print ("Correct!")
        break
    else:
        print ("Incorrect. Please try again.")

If you could please help me, that would be wonderful. Thank you in advance.

>Solution :

If you print what the question and answer variables contain before they are compared like so

print(f"question:{question}, answer:{answer}")
    if question == answer: #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
        print ("Correct!")
        break
    else:
        print ("Incorrect. Please try again.")

the output is

Enter how many questions would you like to solve: 1
What is 18 + 2?
Enter here: 20
question:What is 18 + 2?, answer:20
Incorrect. Please try again

From this we can see that while answer is worth 20 the question you are comparing to it contains a string that doesn’t match the answer.
You need to save the user input and the value it is compared to in different variables. Also you are not assigning but comparing in a place you seem to want to assign. Use "=" for assigning and "==" for comparison.
e.g

answer = (int)(input("Enter here: "))
    if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
        question = (num1 + num2)
    elif operator == "-":
        question = (num1 - num2)
    elif operator == "*":
        question = (num1 * num2)
    elif operator == "/":
        question = (num1 / num2)

Leave a ReplyCancel reply