Arthimatic Quiz Not Accepting Correct Answers - python

I am attempting to make an arithmetic quiz, but have run into this issue: Even if I input the correct answer, it seems to ignore the correct answer code and go straight to the incorrect answer code. Basically, it doesn't accept any right answers.
import random
num1 = (random.randrange(10))
num2 = (random.randrange(10))
correct1 = (num1*num2)
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
if ans1 == correct1:
print("Correct! ")
if ans1 != correct1:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
When ran, I get something like this:
What is 3 multiplied by 0? 0
Incorrect.
The correct answer was 0
Note how the answer and my input were the same, but it ran the code for an incorrect answer. Can anyone help me to fix this? I am using Python 3.4.

3 is not equal to "3". The result of a call to input (in Python3) is a string, not a number.
Call int on the user input
...
ans1 = input("What is " + str(num1) + " multiplied by " + str(num2) + "? ")
ans1 = int(ans1)
...

if int(ans1) == correct1:
print("Correct! ")
else:
print(" Incorrect. ")
print(" The correct answer was " + str(ans1))
You must compare numbers with numbers.
You were comparing '3' vs 3

Related

Using Python to make a quiz from a text file

I'm learning Python, and I need to make a mini quiz. The questions and answers are in a text file (called textfile.txt), each on its own line. At the end of the quiz, it will tell the user their score out of three.
I can get my quiz to print out the first question, and when I try inputting an answer no matter what I put (correct answer or incorrect answer), it'll tell me it's incorrect.
In the text file I have the following:
whats 1+1
2
whats 2+2
4
whats 3+3
6
And here is what I have in my .py file:
questions = open("textfile.txt", "r")
content = questions.readlines()
userScore = 0
for i in range(1):
print(content[0])
answer = input("What's the answer: ")
if answer == content[1]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[2])
answer = input("What's the answer: ")
if answer == content[3]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[4])
answer = input("What's the answer: ")
if answer == content[5]:
print("Correct")
userScore + 1
else:
print("Incorrect")
questions.close()
print("You're done the quiz, your score is: ")
print(userScore)
How do I make it read the correct answer and keep track of the users score?
First of all, use .strip() to remove the newline characters. The answers comparison might not always work because of them.
To ask every even row you can use the modulo (%) operator to get the remainder of the current line index after dividing it by two.
If the answer is correct we add 1 to the corrent_answer_count variable that we print in the end.
questions = open(r"textfile.txt", "r")
content = [line.strip() for line in questions.readlines()]
questions.close()
corrent_answer_count = 0
for i in range((len(content))):
if i % 2 == 0:
print(content[i])
answer = input("What's the answer: ")
if answer == content[i + 1]:
print("Correct")
corrent_answer_count += 1
else:
print("Incorrect")
print("Correct answer count: " + str(corrent_answer_count))

Python If always wrong [duplicate]

This question already has answers here:
How does my input not equal the answer?
(2 answers)
Closed 1 year ago.
I don't know why but when answering correctly, it always says it's not equal to the answers.
import random
a = random.randint(1,100)
b = random.randint(1,100)
answer = a + b
print(answer)
print(f"{a} + {b}")
urAnswer = input("Answer : ")
print("Your answer = " + urAnswer)
if urAnswer == answer:
print("You're Correct!")
else:
print(f"You answered {urAnswer}. Which wasn't the correct answer! The Correct Answer was {answer}")
The inputs supplied via input is of type string, Need to convert the input to int. Also you can do a validation for the input.
a = random.randint(1,100)
b = random.randint(1,100)
answer = a + b
print(answer)
print(f"{a} + {b}")
urAnswer = input("Answer : ")
print("Your answer = " + urAnswer)
if int(urAnswer) == answer:
print("You're Correct!")
else:
print(f"You answered {urAnswer}. Which wasn't the correct answer! The Correct Answer was {answer}")
You are comparing a string to an integer.
Make the answer an integer before comparing so the script will work
if int(urAnswer) == answer:

Python, loops - code results do not match expected outcome

I am trying to make a program for basic addition(+) on mathematics. My code is as follows:
import random
Totalrounds = input("Input how many rounds you want try? ")
answerlist = list()
for i in range(0, int(Totalrounds)):
numb1 = random.randint(0,9)
numb2 = random.randint(0,9)
print(numb1, "+" , numb2,)
Answer = int(input("Your answer is? " ))
if Answer == numb1 + numb2 :
print("Your answer is correct")
print()
else:
print("Your answer is wrong")
print("the right answer is ", numb1 + numb2)
print()
answerlist.append(Answer)
#Result
print("this is your Answersheet from" ,Totalrounds, "question")
for i in range(0, len(answerlist)):
if answerlist[i] == numb1 + numb2 :
Result1 = "correct"
print (numb1, "+" , numb2, "=" ,answerlist[i], Result1 ,)
else:
Result1 = "wrong"
print (numb1, "+" , numb2, "=" ,answerlist[i], Result1 ,)
If I put totalrounds around 5, on #result print, the question 1 - 4 will have different number from upper list. can anyone tell me what I did wrong in this code and what can i do to make it same like upper list question ?
question = numb1 "+" numb2
thank you for you help
There are several things that are problematic or style related in your code.
In the second for loop you try to access the numb1/numb2 but they are not relevant because each iteration of the first for loop you change them so to overcome this issue you need to store them as well.
There is no need to set range to start from 0, this is the default value.
When initiating a list there is no need to do list() just [] is enough.
a correction to your code is as follows:
import random
Totalrounds = input("Input how many rounds you want try? ")
answerlist = []
numb1_list = []
numb2_list = []
for i in range(int(Totalrounds)):
numb1 = random.randint(0,9)
numb1_list.append(numb1)
numb2 = random.randint(0,9)
numb2_list.append(numb2)
print(numb1, "+" , numb2,)
Answer = int(input("Your answer is? " ))
if Answer == numb1 + numb2 :
print("Your answer is correct")
print()
else:
print("Your answer is wrong")
print("the right answer is ", numb1 + numb2)
print()
answerlist.append(Answer)
#Result
print("this is your Answersheet from" ,Totalrounds, "question")
for i in range(len(answerlist)):
if answerlist[i] == numb1_list[i] + numb2_list[i] :
Result1 = "correct"
print (numb1_list[i], "+" , numb2_list[i], "=" ,answerlist[i], Result1 ,)
else:
Result1 = "wrong"
print (numb1_list[i], "+" , numb2_list[i], "=" ,answerlist[i], Result1 ,)
You store the values of the answers in answerlist but you only store the most recent values of numb1 and numb2 so they are always printed as the same.
If you want to print all the previous questions you should store them in a list too.
Then change the print statement at the end
print (numb1list[i], "+" , numb2list[i], "=" ,answerlist[i], Result1)

Why is my code saying the answer is wrong when its right?

The code is supposed to be a simple maths quiz, however, when I enter the correct answer, it says it's wrong. My code is:
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
if student == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
Any ideas?
You forgot to cast the user input to int, so replace student = input() with student = int(input()), as at the moment you are comparing str to int.
Assuming that you are using Python 3, you need to type cast input() to int() in order to compare it with answer which is an integer:
student = int(input())
Assuming python3. The following is not valid for python2, as input treats an integer input as integer.
input() in python2 evaluates the expression with eval() function after reading from stdin, thus returning an integer.
The problem relies on the fact you are comparing strings to answer that is an integer.
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
#Cast the input to an integer for comparison
if int(student) == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
As many have already said, you need to cast the user input to int, replace student = input()
Also, you can do question += 1, rather than question = question + 1. This can help speed you up.

Apparently I cannot achieve the correct answer, everything I input is wrong? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
Okay so I made my own Multiplication Game for my AS Computing course, but I'm running into a number of issues, mainly this occurring around this line:
if ans == result:
print ("That's right -- well done.\n")
solved = solved + 1
else:
print ("No, I'm afraid the answer is %d.\n" % result)
return solved"
The problem seems to present itself. When playing this Multiplication Game any answer that you input, seems to always be incorrect. I've posted the entire of my game below in hopes that someone can help me <3
Thanks in advance!
from random import *
solved = 0
total_num_q = 0
def play(num1, num2, type, solved):
""" The main play function"""
def sp_type():
type = input("Specify the question type: Multiplication: M, Addition :A, Subtraction: S, Division: D: ")
if type not in ['M','A','S','D']:
print("Please input only enter a valid character: ")
return type
type = ""
while type not in ['M','A','S','D']:
type = sp_type()
if type == "M":
ans = input("What's %d times %d? " % (num1, num2))
result = num1 * num2
if type == "A":
ans = input("What's %d plus %d? " % (num1, num2))
result = num1 + num2
if type == "S":
ans = input("What's %d minus %d? " % (num1, num2))
result = num1 - num2
if type == "D":
ans = input("What's %d divided by %d? " % (num1, num2))
result = num1/num2
if ans == result:
print ("That's right -- well done.\n")
solved = solved + 1
else:
print ("No, I'm afraid the answer is %d.\n" % result)
return solved
All fixed now, just took some tweaking. The issue was solved by Bruno and Chris, the error was that my inputs weren't integers, after changing the inputs, the code is working perfectly. Thanks to everyone who helped!
Not so sure, but have you checked the variable types? num1 and num2 should obviously be numerical (int?). Maybe input is string?

Categories