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.
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 = (num1, operator, num2) #e.g. What is 6 - 2 print (question) guess = (int)(input("Enter here: ")) answer = 0 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 guess == answer: #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't. print ("Correct!") continue else: print ("Incorrect. Please try again.")
However, the drawback is that the same question repeats everytime (I am using my old laptop, so the p button and the quotation button is broken). Now my question is how to make the questions not repeat themselves.
Advertisement
Answer
There are a couple problems.
- You are testing for equality with “==” inside the “if” statements, when you probably would like to assign the true answer to a variable to compare to the user’s guess
- You are comparing the answer to the question, which is a string, which will never be equal
Fix the first one by creating a new variable for the true answer to keep it separate from the guess. Fix the second by comparing the guess to the real answer.
guess = (int)(input("Enter here: ")) answer = 0 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 answer == guess : #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't. print ("Correct!") break