how do i make my python code work? random math quiz - python

This is my code it has to have + - * in the code and it has to be chosen randomly but it does not work it does not say the correct answer I would appreciate any help thanks.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
answer = (number1,op,number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1

You need to op as a key to get the appropriate value from the ops dict and call it on the two numbers:
answer = ops[op](number1, number2)
Your code is comparing an int to a tuple i.e 9 == (3, '+', 6)
You may also want to keep the larger number on the left and smaller on the right unless you want negative numbers.
answer = ops[op](max(number1,number2),min(number1, number2))
Also unless this is in a while loop question_number = question_number + 1 is not going to do much.

you need to make the op an op and not a string.
this is your code fixed.
import random
import operator
question_number = 0
score = 0
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))
print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
if op == "+":
answer = (number1+number2)
elif op == "-":
answer = (number1-number2)
elif op == "*":
answer = (number1*number2)
elif op == "/":
answer = (number1/number2)
if user_input == answer:
print("Well done")
score = score + 1
else:
print("WRONG!")
print("The answer was",answer)
question_number = question_number + 1
you could add a while loop to make it repeating

Related

Implementing a timer into Math game in Python

import random
from tkinter import *
import tkinter as tk
import time
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a better score\n")
username = True #this makes sure the user can only enter characters a-z
while username:
name = input("What is your name? ")
if not name.isalpha():
print("Please enter letters only")
username = True
else:
print("Ok,", name, "let's begin!")
main()
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
quit()
#easy
elif choice == "1":
print("Easy Level")
easy_level()
#medium
elif choice == "2":
print("Medium Level")
medium_level()
#hard
elif choice == "3":
print("Hard Level")
hard_level()
#extreme
elif choice == "4":
print("Extreme Level")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
from GUI import dashboard
dashboard()
else:
print("Sorry but", choice, "isn't a vaild choice.")
def easy_level():
global score
#easy level
for i in range(10):
operator_sign =""
answer = 0
num1 = random.randint(1,5)
num2 = random.randint(1,5)
operator = random.randint(1,4)
#choosing the operator randomly
if operator == 1:
operator_sign = " + "
answer = num1 + num2
elif operator == 2:
operator_sign = " - "
answer = num1 - num2
elif operator == 3:
operator_sign = " * "
answer = num1 * num2
elif operator == 4:
operator_sign = " / "
num1 = random.randint(1,5) * num2
num2 = random.randint(1,5)
answer = num1 // num2
else:
print("That is not a vaild entry!\n")
#outputting the questions along with working out if it's correct
question = str(num1) + operator_sign + str(num2) + "\n"
user_input = int(input(question))
if user_input == answer:
score = score + 1
#total score
print("You scored:", str(score), "out of 10")
Been trying to add a timer in this game for a while but every time I go to the first level it doesn't work with the game at the same time, as in I will load the first level and none of the questions will pop-up until the timer has completed. Was wondering if anyone could help me or know a fix to this, I want to make it so if the user completes the test within a certain amount of time they get an additional 10 points added to the overall score. This is what I had come up with at first:
def timer():
countdown=120
while countdown >0:
time.sleep(1)
score = score + 10

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?
# Controlled Assessment - Basic Times Table Test
import random
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is' ,Number1,Operator,Number2)
Answer= input ("Please Type Your Answer: ")
realanswer = (Number1,Operator,Number2)
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The code that needs to assign to the list of operators is...
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
It should work out the answer to each question using the function I'm telling the program that if the operator from the operator list is * to work out Number1*Number2
The current output for telling them if the answer is correct or not prints
Your answer is incorrect, the correct answer is Number1*Number2.
when if the question is what is 10*3 it should be printing
Your answer is incorrect, the correct answer is 30.
Now that I have this code...
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The program always prints that the question is incorrect even with the correct answer inputted, it will then print the correct answer, how would I make it so that It would tell them if it's correct too?
The operator module implements basic operations as functions. Define a dict that maps operator symbols such as "+" to the operator function then use that map to do the calculation.
import random
import operator
op_map = {'+':operator.add, '-':operator.sub, '*':operator.mul}
op_list = list(op_map.keys())
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
Operator =random.choice(op_list)
print ('what is' ,Number1,Operator,Number2)
while True:
try:
Answer= int(input("Please Type Your Answer: "))
break
except ValueError:
print("Must be an integer... try again...")
realanswer = op_map[Operator](Number1, Number2)
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
To perform multiple check like this you can use if, elif statements:
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
For your reference: Python Docs
...
def realanswer(Num1, Op, Num2):
return {
'+': Num1 + Num2,
'-': Num1 - Num2,
'*': Num1 * Num2,
}[Op]
for q in range(2):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is',Number1,Operator,Number2)
userInput = input("Please Type Your Answer: ")
Answer = 0
try:
Answer = int(userInput)
except ValueError:
print("Input not convertible to int!")
rAnswer = realanswer(Number1,Operator,Number2)
if Answer == rAnswer:
print("Correct!")
else:
print("Incorrect...")

Loop in a loop 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 7 years ago.
Improve this question
is there a way to add a second loop to a code. So the question says to create a quiz which I've done however, for the last hour I've being trying to add a second loop so the quiz does it three times:
import random
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print(
"Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?")
while questions < 10:
for i in range(10):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
if op == "-":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" - "+str(number2)+"=")
if uinput == str(subtract):
score += 1
print("Correct, your score is: ", score,)
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
if op == "+":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" + "+str(number2)+"=")
if uinput == str(addition):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
if op == "*":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" * "+str(number2)+"=")
if uinput == str(multiply):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
First, please consider using functions in your code. Functions make everything neater and functions help make code reusable.
Second, there are a lot of areas where the code is superfluous. It is performing unnecessary checks in spots and several sections of the code could be rearranged to reduce the overall length and increase readability.
Nonetheless, here's a revised version of your code with some of those suggestions implemented:
import random
def RunQuiz():
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?\n>>> ")
# End while input
# Run the 10 question quiz
for questions in range(1,11):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
print("Please enter your answer.")
print(" Question" + str(questions) "/10")
if( op == "-"):
# Subtraction
uinput = input(str(number1)+" - "+str(number2)+"=")
# Make it an int for proper comparison
uinput = int(uinput)
if uinput == subtract:
score += 1
print("Correct, your score is: %d" %(score,))
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
elif( op == "+"):
# Addition
uinput = input(str(number1)+" + "+str(number2)+"=")
uinput = int(uinput)
if uinput == addition:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
elif( op == "*" ):
# Multiplication
uinput = input(str(number1)+" * "+str(number2)+"=")
uinput = int(uinput)
if uinput == multiply:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
# End if( op )
# End For 10 questions
print("\nFinal Score: %d/10" % (score,))
# End RunQuiz()
def main():
# Run the quiz 10 times
for RunCount in range(3):
print("Running quiz #%d\n" % (RunCount,))
RunQuiz()
# End For
# End main
# Call main on script execution
main()
Obviously you can rearrange the code to suit your needs. (For example, I did not know if you want the name & class number to be entered every time).
If you want the whole thing to run 3 times then put for i in xrange(3): above the first lines of the quiz then indent the rest of the code to the loop. If that is what you actually want. Good luck!

Always Says Its The Wrong Answer?

I'm making a simple maths quiz its working fine except when I ask if its the correct answer it always says Incorrect if its correct or not. I'm not sure where I went wrong any help on this would be appreciated.
import random
QuestN = 1
QNC = 0
CS = 0
WS = 0
while True:
#Number Of Questions:
QNC = QNC + 1
if QNC == 10:
break
#Choosing The Questions
ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(1,10)
operation = random.choice(ops)
#Simplifying The Operations
if operation == "+":
NEWOP = "+"
elif operation == "-":
NEWOP = "-"
elif operation == "*":
NEWOP = "x"
elif operation == "/":
NEWOP = "รท"
#Asking The Questions
print("Awnser This:")
print(num1)
print(NEWOP)
print(num2)
maths = eval(str(num1) + operation + str(num2))
#Awnsering The Questions
PLAYERA = input(": ")
print(maths)
#Keeping Score
if PLAYERA == maths:
print("Correct")
CS = CS +1
else:
print("Incorrect")
WS = WS +1
print()
#RESTART
The variable PLAYERA will be a string. The variable maths will be an integer. In Python, "7" isn't the same thing as 7, so your if statement will never be true.
You therefore need to this:
if int(PLAYERA) == maths:
print("Correct")
CS = CS +1
Note that this code will cause an error it the player's input isn't a number. You could avoid that by doing this instead:
if PLAYERA == str(maths):
print("Correct")
CS = CS +1

python - ask random mathematical questions not quite working

I need help with this program that I'm writing. It asks random mathematical questions. It chooses between +, - and x. Here's my code
import random
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
choice = random.choice("+-x")
finish = False
questionnumber = 0
correctquestions = 0
while finish == False:
if questionnumber < 10 | questionnumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionnumber = questionnumber + 1
if choice==("+"):
realanswer = number1+number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
if choice==("x"):
realanswer = number1*number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
elif choice==("-"):
realanswer = number1-number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
else:
finish = True
else:
print("Good job",name,"! You have finished the quiz")
print("You scored " + str(correctquestions) + "/10 questions.")
questions()
The output:
What is your name: s
Hello there s !
6 - 9
What is the answer?-3
That's the correct answer
9 - 8
What is the answer?1
That's the correct answer
9 - 7
What is the answer?2
That's the correct answer
8 - 3
What is the answer?4
Wrong answer, the answer was 5 !
5 - 6
What is the answer?1
Wrong answer, the answer was -1 !
8 - 7
What is the answer?1
That's the correct answer
3 - 5
What is the answer?2
Wrong answer, the answer was -2 !
4 - 5
What is the answer?1
Wrong answer, the answer was -1 !
7 - 2
What is the answer?5
That's the correct answer
7 - 1
What is the answer?6
That's the correct answer
Good job s ! You have finished the quiz
You scored 6/10 questions.
Now the program is running fine but it asks the questions with the same operator (+, -, x) every time I start the program a different operator questions happen but I want to run it so it actually asks different adding, subtracting, multiplication questions inside the program so all the questions that it asks it will be different questions like x, + and - every different question.
It should help if you move the choice part inside the loop:
while not finish: # better than finish == False
choice = random.choice("+-x")
# etc
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = ranom.randint(1, 100)
num2 = radom.randint(1, 100)
symbol = rndom.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Wong u wetard")
correct = correct + 1
else:
print("correct")
print(name, ", You Got", correct, "Out Of 10")
After while finish == false put this !
choice = random.choice("+-x")
I have attempted the same problem that you face, and after looking at your code I made the changes detailed below. the code works and it is (relatively) neat and concise.
def name_enter():
global name
name = ""
while name == "" or len(name) > 25 or not re.match(r'^[A-Za-z0-9-]*$', name):
name = input("Please enter your name: ")
enter_class()
def enter_class():
global class_choice
class_choice = None
while class_choice not in ["1","3","2"]:
class_choice = input("Please enter you class (1, 2, 3): ")
print("\nClass entered was " + class_choice)
mathsquestion()
def mathsquestion():
global qa, score
qa, score = 0, 0
for qa in range(0,10):
qa = qa + 1
print("The question you are currently on is: ", qa)
n1, n2, userans = random.randrange(12), random.randrange(12), ""
opu = random.choice(["-","+","x"])
if opu == "+":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ")
prod = n1 + n2
elif opu == "-":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ")
prod = n1 - n2
else:
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ")
prod = n1 * n2
userans = int(userans)
prod = int(prod)
if prod == userans:
score = score + 1
print("Well done, you have got the question correct. Your score is now: %d" % (score))
else:
print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))
print("Your final score is: %d" % (score))
name_enter()
This is a very different code but should do the same thing. It's also much shorter and neater.
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
symbol = random.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, ", You Got", correct, "Out Of 10")

Categories

Resources