Implementing a timer into Math game in Python - 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

Related

python checking time to board plane - if not in 45 minutes, then calculates how long to wait

Ok so I am creating a program so that the user inputs their plane departure time
if the plane departure time is within 45 minutes of current (strftime) then they can procees to board
else, they are told how long until they can make way to gate
e.g. their plane leaves at 8.00 and current time is 7.00 (they cant board yet) so it says they have to wait for 15 minutes
bag = 0
minute = 0
array = []
f_row = ""
f_col = ""
name = ""
x = 0
from time import strftime
def weight():
global bag
print("Bag checking section")
print("")
bag = int(input("Enter weight of your bag: "))
if bag >= 23:
bag += 1
print("You need to pay £4 per extra KG")
print("New total to pay is: £",bag * 4)
elif bag > 0 and bag < 23:
print("Price: free")
else:
print("Try again")
def exchange():
print("Welcome to our exchange system")
print("")
money = float(input("How much money to exchange: £"))
print("1 for DOLLARS")
print("2 for RUPEE")
choice = input("Option: ")
if choice == "1":
print("£",money,"exchanged to $",round((money * 1.35)))
elif choice == "2":
print("£",money,"exchanged to ₹",round((money * 99.40)))
def boarding():
print("Check to see how long until you can board")
print("")
departure = input("Enter time of flight in 24h format: ")
hour = departure[0]+departure[1]
minute = departure[2]+departure[3]
print(hour,minute)
time = minute - 45
print(time)
def seats():
print("")
print("Choose your seats")
print(" ")
name = input("Enter name: ")
f_row = int(input("Enter row to sit in: "))
f_col = int(input("Enter column number: "))
grid = []
print("")
if array[f_row][f_col] != "empty":
print("Seat taken, try again")
elif array[f_row][f_col] == "empty":
array[f_row][f_col] = name
def make():
for x in range(10):
array.append([])
for y in range(7):
array[x].append("empty")
def show():
for row in range(10):
for col in range(7):
symbol = array[row][col]
print(symbol, end = " ")
print()
#main
while True:
print("")
print(strftime("%H:%M%p"))
print("")
print("1 to weigh bag")
print("2 for exchange")
print("3 for time until you can get on plane")
print("4 for choosing seat")
print("5 to exit program")
print("")
choice = input("Option: ")
print("")
if choice == "1":
weight()
elif choice == "4":
make()
show()
seats()
make()
show()
elif choice == "5":
break
elif choice == "2":
exchange()
elif choice == "3":
strftime("%H:%M%p")
print("")
boarding()
else:
print("Try again")
please note I have just started python and will not understand lots of complex code
if possible can it be reallt basic how to do this? thanks

Game of Chance in Python 3.x?

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"
The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

Python - while loop semi works depending on where i start on the menu

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")

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")

I don't understand why a NameError is thrown in my game

Code:
import random
score = 0
score2 = 0
guess = 0 #Defining Variables
quiz = 0
lives = 3
print('''Would you like to play a 'Guess the number' or a '3 round quiz'?
For Guess the number enter '1', for 3 round quiz enter '2' ''')
game = input()
if game == ("1"):
guess = guess + 1
print("Ok, time to start") #Asking what game you want to play
elif game == ("2"):
quiz = quiz + 1
else:
print("Please answer with 'Guess the number game' or a '3 round quiz'")
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
if difi == ("Easy"):
print("Ok, let's go!") #Choosing difficulty
score = score + 1
elif difi == ("Hard"):
print("Ok,let's go")
score2 = score2 + 1
else:
print("Please answer with 'Easy' or 'Hard'")
if score == 1:
num1 = (random.randint(1, 50))
num2 = (random.randint(1, 50))
print("First question")
print("What is ",num1,"+",num2) # Question 1 easy
ans1 = input()
ans1 = int(ans1)
if ans1 == num1+num2:
print("Well done")
score = score + 1
else:
print("Unlucky, it was ",num1+num2)
if score == 2:
num3 = (random.randint(1, 10))
num4 = (random.randint(1, 10))
print("Next question")
print("What is ",num3,"*",num4) # Question 2 easy
ans2 = input()
ans2 = int(ans2)
if ans2 == num3*num4:
print("Congratualtions, on to the last question")
score = score + 1
else:
print("Unlucky, it was ",num3*num4)
if score == 3:
num5 = (random.randint(1, 5))
num6 = (random.randint(1, 2))
print("What is ",num5,"**(To the power of)",num6) # Question 3 easy
ans3 = input()
ans3 = int(ans3)
if ans3 == num5**num6:
print("Congratualtions, you beat the game on easy")
print("Now try hard!")
score = score + 1
else:
print("Unlucky, it was ",num5**num6)
if score == 4:
print("Would you like to try hard?")
hard2 = input()
else:
print("Ok, come back later") # If you beat easy you can choose to play hard here
if hard2 == ("Yes"):
print("This is the hard game, good luck!")
score2 = score2 + 1
elif hard2 == ("No"):
print("Ok, see you soon")
else:
print("Please answer with 'Yes' or 'No'")
if score2 == 1:
num12 = (random.randint(1, 500))
num22 = (random.randint(1, 500))
print("First question")
print("What is ",num12,"+",num22) # Question 1 hard
ans12 = input()
ans12 = int(ans12)
if ans12 == num12+num22:
print("Well done")
score2 = score2 + 1
else:
print("Unlucky, it was ",num1+num2) #2s in front of all hard variables so it differentiates the variables #From Easy and Hard
if score2 == 2:
num32 = (random.randint(1, 25))
num42 = (random.randint(1, 25))
print("Next question")
print("What is ",num32,"*",num42) # Question 2 hard
ans22 = input()
ans22 = int(ans22)
if ans22 == num32*num42:
print("Congratulations, on to the last question")
score2 = score2 + 1
else:
print("Unlucky, it was ",num32*num42)
if score2 == 3:
num52 = (random.randint(1, 15))
num62 = (random.randint(1, 3))
print("What is ",num52,"**(To the power of)",num62) # Question 3 hard
ans32 = input()
ans32 = int(ans32)
if ans32 == num52**num62:
print("Congratualtions, you beat the game on hard")
else:
print("Unlucky, it was ",num52**num62)
if guess == 1:
print("Time to play") #Guess the number game
guess = guess + 1
if guess == 2:
print("Pick a number between 1 an 10")
comp_num = (random.randint(1,10))
user_guess1 = input()
user_guess1 = int(user_guess1)
if user_guess1 == comp_num:
print("Well done, you beat the game on your first turn!")
else:
print("Unlucky you still have 2 more goes")
lives = lives - 1
if lives == 2:
print("Guess again")
user_guess2 = input()
user_guess2 = int(user_guess2)
if user_guess2 == comp_num:
print("Congrats, you beat it on your second guess!")
lives = lives - 1
if lives == 1:
print("Guess again")
user_guess3 = input()
user_guess3 = int(user_guess3)
if user_guess3 == comp_num:
print("Congrats, you beat it on your last life!")
lives = lives - 1
else:
print("Unlucky, care to try again")
if lives == 0:
retry = input()
if retry == ("Yes"):
lives = lives + 3
elif retry == ("No"):
print("Ok, come back soon")
else:
print("Please answer with 'Yes' or 'No'")
Error:
Traceback (most recent call last):
File "C:\Users\Boys\Desktop\3 Round Quiz.py", line 24, in <module>
if difi == ("Easy"):
NameError: name 'difi' is not defined
The error above comes up when I enter '1' to play the game 'Guess the number' it comes up with that, even though the variable difi is for the quiz. I'm not sure why this happens so any help will be appreciated!
Thanks
difi is only ever bound if quiz is 1:
if quiz == 1:
print("Would you like to play 'Easy' or 'Hard'?")
difi = input()
You don't set difi otherwise, and the name is not defined in that case.
quiz starts at 0, and isn't incremented unless you pick '2':
elif game == ("2"):
quiz = quiz + 1
If you pick '1', on the other hand, quiz remains at 0, difi is not set, and your code breaks.
The control flow is reaching the if difi == ("Easy"): line before difi is defined because quiz is still 0 at the top. I suspect you intended the if difi == ("Easy"): and associated parts of the code to be indented more so they appear inside the if quiz == 1: block.

Categories

Resources