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

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.

Related

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 Quiz Game Logic Error

I'm trying to practice python because I'm starting yr 12 soon. I created a quiz game but when i get the question right it always says that it's wrong
print("Welcome to the math quiz game!")
for i in range(0,10):
operators = ['+','-','*','/']
import random
num1 = random.randint(1,10)
num2 = random.randint(1,10)
randop = random.choice(operators)
question = input("What is %d %s %d: " % (num1,randop,num2))
if randop == "+":
answer = num1 + num2
elif randop == "-":
answer = num1 - num2
elif randop == "*":
answer = num1 * num2
elif randop == "/":
answer = num1 / num2
if question == answer:
print("\nCorrect")
elif question != answer:
print("Incorrect or Invalid")
When doing a comparison in a program with == we must compare two variables of the same type (which can be devious when starting Python). Answer is a number, while question is a string which was written by the user. Thus Python recognizes the two as different and false. To avoid this you must either convert the number to a string or the string to a number so you compare two variables of the same type.
As mentioned you need to cast the return value from input() into an float (to cope with decimals from division):
question = float(input("What is %d %s %d: " % (num1,randop,num2)))
I don't recommend doing this as a bad input will crash the game so use input validation with a try/except block:
question = input("What is %d %s %d: " % (num1,randop,num2))
try:
question = float(question)
except ValueError:
print('Invalid or incorrect.')
continue # skip the rest of the code and head straight into the next iteration in the for loop
Also, I don't recommend including the division option as most values will be recurring decimals which cannot be input correctly unless you check beforehand that the answer will not be recurring or if you round the answer off to, say, 2 decimal places and ask the user for a 2 d.p answer
(You could also make the 'answer' variable a string instead of making 'question' an int)

Issue in providing special character as input in python [duplicate]

I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.

Program gives unexpected output -- why?

I am writing a program which will test arithmetic skills.
It is supposed to generate random questions, and give a random operation.
Here is my code:
import random
score = 0
counter = 0
ops = ['+', '-', '*', '/']
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
question = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
def points():
while counter < 10:
question()
if question == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
points()
print(f"\nYou got {score} out of {counter}")
But it gives this output:
What is 9 + 3?: 12
Wrong! The answer is 12
It is supposed to say correct if the input matches the answer, and count a score, and print the score out of ten at the end.
Please help me fix this.
The problem is in
if question == answer:
In that line, question is a reference to the function question() that you defined earlier. Since answer is some int holding the answer to the question, the == is always False. You never actually find out what the user typed in.
To fix that, do something like this:
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
return user_answer
def points():
while counter < 10:
user_answer = question()
if user_answer == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
I've changed the name to make it more clear what's going on.
As an addendum, I would highly, highly recommend not using global variables. They are almost never necessary and generally confuse the issue. For example, I think that
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
real_answer = eval(str(num1) + operation + str(num2))
return user_answer, real_answer
def points():
score = 0
for questions_asked in range(1, 11):
user_answer, real_answer = question()
if user_answer == real_answer:
print("\nCorrect!\n")
score += 1
else:
print(f"\nWrong! The answer is {answer}\n")
This makes it much easier to understand the program flow.
Your question has already been answered by Josh Karpel, but I just thought I'd point out another issue with division.
Division will always result in a float instead of an int, so if the user says 4 / 2 is 2... the script will say the answer is wrong, because it's doing a stringy comparison of "2" with "2.0". That's why in Josh's version, he converts the user answer to a float. This way the answers are compared numerically.
Additionally, the script is currently capable of asking things like What is 4 / 7 ? which is difficult for a person to answer. One work around would be to randomise num2 until it is evenly divisible by num1.
def question():
num1 = random.randint(0, 10)
num2 = random.randint(1, 10)
operation = random.choice(ops)
if operation == '/':
while num1 % num2 != 0:
num2 = random.randint(1, 10)
# do eval

Program keeps going straight to else statement (Python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
number1 = float
number2 = float
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if number1 > number2:
print number1 + ' is bigger than ' + number2
elif number2 < number1:
print number2 + ' is bigger than ' + number1
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
These lines:
number1 = float
number2 = float
do not make the inputs into floats. Instead, all they do is assign the variables to the built-in float.
This is what you should be doing:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
Also, inside your if-statements, you cannot add strings and floats together (trying to do so will raise a TypeError). There are two ways to solve this problem. The first is with str.format:
print '{} is bigger than {}'.format(number1, number2)
The second is to separate the values with commas:
print number1, 'is bigger than', number2
Finally, your logic is a little off. The second if-statement should be like this:
elif number1 < number2:
Otherwise, it does the same thing as the first if-statement.
Below is a fixed version of your script:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
if number1 > number2:
print '{} is bigger than {}'.format(number1, number2)
elif number1 < number2:
print '{} is bigger than {}'.format(number2, number1)
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
You are comparing strings, which means they are compared lexicographically.
Cast the return value of raw_input to float:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
The lines:
number1 = float
number2 = float
merely store references to the float() constructor. Python doesn't have type declarations, and those lines do not mean that the two names should only hold floating point values.
You do then need to turn the floating point numbers back to strings when printing; you could use the fact that print accepts multiple values to have this done for you:
if number1 > number2:
print number1, 'is bigger than', number2
elif number2 < number1:
print number2, 'is bigger than', number1
Alternatively, you could store the raw_input() results as strings and only turn the values to float() when comparing:
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if float(number1) > float(number2):
print number1 + ' is bigger than ' + number2
elif float(number2) < float(number1):
print number2 + ' is bigger than ' + number1

Categories