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")
Related
Disclaimer: I am VERY inexperienced in python(if you couldn't tell by the question)
I made this basic code where you type in a given password. Once you type it in, you can either take a test or change the password. Each choice leads to different dialogue options, and so on(I used a lot of if: else and while: statements).
However, for my code, after getting the test question right, it'll print the "wrong" message WITH the "you got it right" message. Then, when signing in again, you have to type in the password TWICE before it registers your input. Anyone know how to fix this? I'm using Pycharm btw
Code:
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print("New password " + change + " saved. Please sign back in.")
k = 1
t = 1
ans = input("Enter your password: ")
else:
print("Signing out..")
Error message:
hi there you have a small mistake in the sequence of the if statement
when the ans3 is 2 the program rechecks if ans3 is -2 and it finds it false so it runs the code in the else statement to fix this you simply need the program to run else just in case that the two if statements are false
this is achieved by using elif statement in the line " if ans3 == "-2":"
it should be "elif ans3 == "-2":"
In this code here you have a small mistake in last if statement. In last if statement you use 'ans' statement its not needed bcz already you use this for printing a new answer so try my code and run it.its give proper output what ever you need.
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print(" New password " + change + " saved. Please sign back in.")
k = 1
t = 1
else:
print("Signing out..")
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
i am a super beginner to python.
Below is a simple math quiz. The problem is that selecting option 2 (subtraction) then 1 (addition) shuts down the program instead of asking addition problem.
It works from 1 to 2 but it does not work from 2 to 1. Do you guys know what i am missing here? Thanks in advance.
while user_input == 1:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 + num2
problem = str(num1) + " + " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
subtraction for choice 2
while user_input == 2:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 - num2
problem = str(num1) + " - " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
Exit for choice 3 - the User is done with the quiz
else:
print('See you again')
For good practice and readability, I would implement something like:
choice = input()
while choice != -1:
choice = input()
if choice == 1:
#do something
else if choice == 2:
#do something else
else if choice == -1:
print("bye")
Your code is wrong. You must do something like this:
choice = input()
while choice == "1" or choice == "2":
if choice == "1":
#do add
else:
#do subtraction
choice = input()
print("bye")
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!
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