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)
Related
# Pick the numbers you'd like to use
number1 = (input('What is the first number?\n'))
number2 = (input('What is the second number?\n'))
# Choose what to do with those numbers
Choice = input('Would you like to add, subtract, multiply or divide?\n ')
# Where the calculating happens, if it doesn't go through the error message asking you to use numbers will happen
try :
# Converting the numbers from str into float, if this doesnt happen it means numbers were not used
num1 = float(number1)
num2 = float(number2)
if Choice is add :
answer = num1 + num2
elif Choice is subtract :
answer = num1 - num2
elif Choice is divide :
answer = num1/num2
elif Choice is multiply
answer = num1 * num2
print(answer)
# The error message if the numbers you gave werent in numeric form
except :
print('Please choose proper numbers in numeric form instead of letter/words')
This is the code, the issue I get is:
'File "main.py", line 13
elif Choice is subtract :
^
SyntaxError: invalid syntax'
Any help would be appreciated, thanks :). (If this code just wouldn't work at all, please lmk. Im currently going through a book on how to code and thought this would be fun to try since I just learned about booleans and variables)
I think you mean to do this:
if Choice == 'add':
answer = num1 + num2
elif Choice == 'subtract':
answer = num1 - num2
elif Choice == 'divide':
answer = num1/num2
elif Choice == 'multiply':
answer = num1 * num2
Be careful with indentation. If you have a single if / elseif / elseif / elseif / else chain, each condition should be at the same indent level, and each body should match its condition plus one indent (typically 4 spaces or 1 tab).
To compare a string captured from the user with input() to a literal string, you would do:
if Choice == 'add':
You need to specify the quotation marks around 'add', otherwise it would try to reference a variable called add, which isn't defined.
For == vs is when checking the string, see Why does comparing strings using either '==' or 'is' sometimes produce a different result?
Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
I am creating a game in python where I need to run basic math operations. These operations would be provided by a user as input. How do I do this?
So far, I have independent variables for each number and each operator, however, when I run the code, it does not recognize the operator ('+','-','*','/') as an operator, but rather as strings. Therefore, when running the programming it would run as 1'+'1.
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
vsofar = (vinput1, vop1, vinput2)
print(vsofar)
Computer's output:
(1, '+', 1)
While eval operates in a very general context and so much scope for introducing security issues ast.literal_eval is intended to evaluate string literals only and so has a far narrower and hence safer scope.
from ast import literal_eval
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
vsofar = (vinput1, vop1, vinput2)
print(literal_eval(''.join(map(str, vsofar))))
Otherwise create a mapping from operators to functions to lookup the function to call for each operator.
import operator
import sys
ops = {'+': operator.add,
'-': operator.sub}
v1 = int(input('enter first num'))
op1 = input('input operator')
if not op1 in ops:
print('unsupported operation')
sys.exit(1)
v2 = int(input('enter second num'))
print(ops[op1](v1, v2))
The great thing about this is that you don't have to screw around in the program logic to add new (binary) operations. You just add them to the dict, with far less opportunity to make a typo in a long if/elif chain.
The safest and simplest method is to use an if-statement to check which symbol was input. A sample if-statement would be:
print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)
if (vop1 == "-"):
vsofar = vinput1 - vinput2
print(vsofar)
elif (vop1 == "+"):
vsofar = vinput1 + vinput2
print(vsofar)
elif (vop1 == "/"):
vsofar = vinput1 / vinput2
print(vsofar)
elif (vop1 == "*"):
vsofar = vinput1 * vinput2
print(vsofar)
else
print("Invalid operator entered.")
Just to quickly explain, these if-statements check whether the operator entered, which is stored in vop1, matches the -, +, *, or / operator. If it matches any of these, then its respective operation is carried out and stored in the variable vsofar,cwhich is printed in the line after that operation. If none of the operations work, then an invalid statement is printed.
This is the most bland, simple, and somewhat long way of doing it. However, the eval() function is not safe to use. A shorter yet more complex than my way is the answer of Paul Rooney.
Hope this helps!
You Can evaluate!
>>> input1=1
>>> input2=3
>>> vop1="+"
>>> print eval(str(input1)+vop1+str(input2))
4
Have a look at this
Hope this helps!
If you don't want to use eval() you might try a series of conditionals to test the operator and then perform the correct calculation based on that.
if vop1 == "+":
return vinput1 + vinput2
if vop1 == "-":
return vinput1 - vinput2
num1= int(input("first number: "))
num2= int(input("2md number: "))
sign= input("sign operator: ")
if sign == '+':
print("Answer is", num1+num2)
elif sign == '-':
print("Answer is", num1-num2)
elif sign == '*':`enter code here
print("Answer is", num1*num2)
elif sign == '/':
print("Answer is", num1/num2)
else:
print("am not built to use this sign yet")
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?
The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked
import random
name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10)
numbers=random.randint(1,10)
arith=random.choice("+" "-" "/")
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
if arith=="-":
print(number,arith,numbers)
answer=number-numbers
if arith=="/":
print(number,arith,numbers)
answer=number/numbers
while True:
try:
usersanswer= int(input())
except ValueError:
print ("That is not a valid answer")
continue
if usersanswer==answer:
print("correct")
break
else:
print("incorrct")
The validation doesnt work. im not sure why, is there a way to validate a string
I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.
You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.
import random
import operator # contains the python operators as functions
try:
input = raw_input # rebind raw_input to input, if it exists
# so I can just use input :P
except NameError:
pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.
#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
#'/': operator.truediv, #hey, division exists.
#But if you want division to actually work, you'll
#have to introduce a fudge factor :P
}
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
# Brevity :P This is a list comprehension
first_number, second_number = [random.randint(1,10) for _ in range(2)]
oper = random.choice(list(operator_mapping))
answer = operator_mapping[oper](first_number, second_number)
while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
#while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
print('Wrong answer! try again!')
#If I've left the loop, user has given correct (enough) answer
if i <9: # all but last
print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values.
Python 2.7 getting user input and manipulating as string without quotations
Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.
Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.
The else statement does not match any outer indentation.
Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.
EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it.
EDIT: Here is code that shows how it works within a while loop.
import random
from random import randint
name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"
score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
# makes numbers and operator
first_number = randint(1,10)
second_number = randint(1,10)
oper = random.choice("+""-""*")
# determines the problem
if oper == "+":
answer = first_number + second_number
print first_number,second_number,oper
elif oper == "-":
answer = first_number - second_number
print first_number,second_number,oper
elif oper == "*":
answer = first_number*second_number
print first_number, second_number, oper
user_answer = int(raw_input("Your answer: "))
if user_answer != answer:
print 'Wrong answer! try again!'
user_answer = int(raw_input('Your answer: '))
if user_answer == answer: # exits the while loop when the correct answer is given
if question_count < 10:
print 'Well done! Now onto question number {0}'.format(question_count+1)
score_count += 1
elif question_count == 10:
print 'Well done! You are done!'
score_count += 1
else:
print 'Something is wrong.'
question_count += 1 # updates the variable
# GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)
Happy coding! and best of luck!
hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:
import random #random module automatically downloaded when you install python
name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10) #creating a random number
numbers=random.randint(1,10) #creating a random number
list = ["+","-","/"] #creating a list (or sometimes called array)
arith=random.choice(list) #getting random operators from list (+,-,/)
question += 1 #basically means add one to question variable each time in loop
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
elif arith=="-":
print(number,arith,numbers)
answer=number-numbers
elif arith=="/":
print(number,arith,numbers)
answer=number/numbers
answer = int(answer)
#from HERE
useranswer = "initialising this variable"
while useranswer == "initialising this variable":
try:
usersanswer= int(input())
if usersanswer==answer:
print("correct")
break
else:
print("incorrect")
except ValueError:
print ("That is not a valid answer")
#to HERE it is input validation this takes a while to explain in just commenting
#but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
#and paste into google for a detailed video !!!!!!
I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python