How to implement a timer for a math quiz in python? - python-3.x

import random
import time
import pathlib
import hashlib
import operator
level = 1
score = 1
def sign_up():
username = input("Enter a username: ")
while True:
password = input("Enter a password (6 character long): ")
if len(password) < 6:
password = input("Enter a password (6 character long): ")
else:
break
hashed_password = hashlib.sha1(password.encode("utf-8")).hexdigest()
# print(hashed_password)
with open("credentials.txt", mode="w") as writable_password:
writable_password.write(username+"\n")
writable_password.write(hashed_password+"\n")
log_in()
def log_in():
print("Please, enter your usarname and password to sign in")
username = input("Username: ")+"\n"
while True:
password = input("Password (6 character long): ")
if len(password) < 6:
password = input("Password (6 character long): ")
else:
break
with open(".credentials.txt", mode="r") as credentials:
user_data = credentials.readlines()
for i in user_data:
# print(i)
if i == username and hashlib.sha1(password.encode("utf-8")).hexdigest()+"\n" == user_data[user_data.index(i)+1]:
print("You have succesfully signed in")
start_game()
break
def start_game():
start = "ll"
start = input("Please press any key to start the game")
# print(start)
if start != "ll" and level == 1:
level_one()
overall = 0
def level_one():
global score
global overall
if score <= 0:
return print("Haha, You lost")
answer = 0
first_number = random.randint(1, 100)
second_number = random.randint(1, 100)
random_operator = random.choice(["+", "-"])
if random_operator == "+":
response = input(f"{first_number} + {second_number}: ")
answer = first_number + second_number
if int(response) == answer:
score += 10
overall += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
else:
response = input(f"{first_number} - {second_number}: ")
answer = first_number - second_number
if int(response) == answer:
score += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
# print(first_number, second_number, answer)
# def main():
# if __name__ = "__main__":
# main()
# sign_up()
# log_in()
start_game()
I want to implement a timer for my math quiz. The user should have 2 minutes at the beginning and for each correct answer 10 seconds will be added. For wrong answers 6 sec will be removed. How can I do this with Python 3.8?

I would add a new methode and using the threading.Timer modul (https://docs.python.org/3/library/threading.html#timer-objects):
from threading import Timer
global time_to_play
time_to_play=2*60 # in seconds
....
def check_for_end:
if time_to_play == 0: # time runs out
print("You lose")
exit(0) # exit program
else: # still playing
t = Timer(2.0, check_for_end) # start Timer wich runs the check methode in 2 sec
t.start()
and now you just have to adjust the global variable time_to_play accordingly.
The Timer will check all 2 seconds, if time_to_play is 0

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

How do I make the program roll the previous number of dice by just clicking enter?

This is what I have so far. It works great if you want to roll different amounts of dice each time, but if you are playing a game like Sequence Dice its can get pretty frustrating and monotonous. I want it to be able to roll the previous number of dice rolled when you click enter without having to enter a new value.
from random import randint
run = False
dice_num = 0
roll_num = 0
total_sum = 0
print()
print("Welcome to dice roller!")
print()
print("To quit, just type stop at any time.")
while run == False:
print()
num_of = input("How many dice do you want to roll? ")
print()
if num_of.lower() == "stop":
print()
print("Thank you!")
print(f"You rolled a total of {dice_num} dice in {roll_num} rolls.")
print()
break
try:
act_num = int(num_of)
print("You rolled...")
roll_num += 1
while act_num > 0:
dice_out = randint(1, 6)
print(dice_out)
act_num -= 1
dice_num += 1
total_sum += dice_out
print()
print(f"Sum: {total_sum}")
total_sum = 0
except ValueError:
print("Try Again.")
run == False```
I think this should do the job. I created variable previous_dice_num At the end of each loop, the value of num_of will be stored in previous_dice_num. Then, whenever the user enters nothing, the value of previous_dice_num will be used as num_of.
from random import randint
run = False
dice_num = 0
roll_num = 0
total_sum = 0
previous_dice_num = 0
print()
print("Welcome to dice roller!")
print()
print("To quit, just type stop at any time.")
while run == False:
print()
num_of = input("How many dice do you want to roll? ")
print()
if num_of == '':
num_of = previous_dice_num
if num_of.lower() == "stop":
print()
print("Thank you!")
print(f"You rolled a total of {dice_num} dice in {roll_num} rolls.")
print()
break
try:
act_num = int(num_of)
print("You rolled...")
roll_num += 1
while act_num > 0:
dice_out = randint(1, 6)
print(dice_out)
act_num -= 1
dice_num += 1
total_sum += dice_out
print()
print(f"Sum: {total_sum}")
total_sum = 0
except ValueError:
print("Try Again.")
previous_dice_num = num_of

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

Python Error handling for an input requiring a integer

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

My code runs until the last line, input is needed

print("Welcome to my calorie counter program")def disp_menu():choice_list = ["a", "d", "m", "q"]
initial loop
while True:
print("What do you want to do?")
print("a = add an item")
print("d = delete an item")
print("q = quit")
choice = input("make a selection>")
if choice in choice_list:
return choice
else:
print("not a valid selection, try again")
while True:
choice = disp_menu()
if choice == "a":
tot_cals, item_cnt = add_process(tot_cals, item_cnt)
elif choice == "d":
del_item()
elif choice == "q":
break
disp_meal()
#create lists
item_list = [] #list of items ordered
cals_list = [] #
#create variables
cont = str("y")
item_cnt = int(0)
tot_cals = int(0)
#define functions here
#calculates calories per grams
def calc_cals(g_type, grams):
if g_type =="f":
return grams * 9
else:
return grams * 4
#first loop
while cont.lower() =="y":
valid_data = False #this is the boolean flag for data validation
#Capture input
while not valid_data:
item_name = input("please enter the item> ")
if len(item_name) > 20:
print("not a valid food name")
elif len(item_name) == 0:
print("you need to enter a name")
else:
valid_data = True
#reset the flag for the next data item
valid_data = False
while not valid_data:
try:g_carbs = int(input("enter grams of carbs> "))
except Exception is detail:
print("carbs error: ", detail)
else:
valid_data = True
#reset the flag for the next data item
valid_data = False
while not valid_data:
try:g_fats = int(input("enter grams of fats> "))
except Exception is detail:
print("fats error: ", detail)
else:
valid_data = True
valid_data = False
while not valid_data:
try:g_protein = int(input("enter grams of protein> "))
except Exception is detail:
print("protein error: ", detail)
else:
valid_data = True
new function
def add_process(tot_cals, item_cnt):
item_name = input_name()
g_carbs = input_grams("carbs")
g_fats = input_grams("fats")`
g_prot = input_grams("protein")
#Do the math
cals = calc_cals("c", g_carbs) + calc_cals("f", g_fats) + calc_cals("p", g_prot)
#output
print("total calories for {} are {}".format(item_name, cals))
incl = input("do you want to include {}? (y/n)>".format(item_name))
if incl.lower() == "y":
add_item(item_name, cals)
#accumulate totals
tot_cals = tot_cals + cals
item_cnt += 1 #shortcut method
print("item {} entered.".format(item_name))
else:
print("Item {} not entered.".format(item_name))
return tot_cals, item_cnt
#new function
def del_item():
if len(item_list == 0):
print("you have no items to delete")
else:
print("\nDelete an item")
disp_meal()
valid_data = False
while not valid_data:
try:
choice = int(input("Enter the item number you want to delete>"))
if 1<= choice <= len(item_list):
choice = choice - 1
print("Item {}. {} with {} calories will be deleted".format(choice + 1,
item_list[choice],
cals_list[choice]))
del item_list[choice]
del cals_list[choice]
valid_data = True
except Exception as detail:
print("error: ",detail)
print("try again")
#new function
def disp_meal():
print("\nMeal Calorie Counter")
print("Num\tItem\t\tcals")
print("---\t----\t\----")
meal_cals = 0
for c in range(len(item_list)):
meal_cals += cals_list[c]
print("{}.\t{}\t\t{}".format(c+1,item_list[c],
print("\nYour meal has {} items for a total of {} calories\n".format(len(item_list), meal_cals)
print("-" * 20)
#this last line gives me an eof error

Resources