append variable values to specific folder/file - python

I need to append a the name and the score to a specific class folder and file at the end of the program,
print("You scored " + str(correctquestions) + "/10 questions.")
The student chooses what class they're in, after the end of the questions I want it to write to their class folder and text file they're name and score.
import random
import time
import sys
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
time.sleep(0.5)
print("What class are you in?")
time.sleep(0.5)
print("")#space
whatClass=input("Enter 1, 2 or 3: ")
print("")#space
if whatClass == "1":
print("You are in class 1!")
elif whatClass =="2":
print("You are in class 2!")
elif whatClass =="3":
print("you are in class 3!")
else:
print ("Please try again")
quit()
finish = False
questionnumber = 0
correctquestions = 0
while not finish:
choice = random.choice("+-x")
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.")
#if the class is 1 append the name and score to folder class1
#if the class is 2 append the name and score to folder class2
#if the class is 3 append the name and score to folder class3
questions()

I think you want something like this:
import errno
folder= 'class%s'%whatClass
# create the folder if it does not exist
try:
os.makedirs(folder)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# create a file with the student's name in the folder, and write the score
with open(os.path.join(folder, name+'.txt'), 'w') as f:
f.write(str(score))
Also, please read the python docs on file IO.

Related

Find out how i can improve my Hangman coding on jupyter notebook

enter image description herei want to find out how
i can take in user’s inputs on the number of times user wishes to run/play, and execute accordingly. and also how can i provide user with an option on the game/run mode
allow the user to choose the complexity level of a game?
include a scoreboard that shows the top 5 players/scores.
[enter image description here](https://i.stack.enter image description hereimgur.com/CcJOM.png)
from IPython.display import clear_output
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
#Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
no_of_time = input("How many times do you want to play: ")
answer_word = list(str.lower(input("input enter your word: "))) #https://stackoverflow.com/questions/1228299/change-one-character-in-a-string
clear_output()
win = False
#defining function
def guesscheck(guess,answer,guess_no):
clear_output()
if len(guess)==1:
if guess in answer:
print("Correct, ",guess," is a right letter")
return True
else:
print("Incorrect, ",guess, " is a not a correct letter. That was your chance number ",guess_no)
return False
else:
print("Enter only one letter")
#Storing the number of characters in different variable
answer_display=[]
for each in answer_word:
answer_display += ["*"]
print(answer_display)
#initializing number of allowable guesses
guess_no = 1
while guess_no<5:
clear_output
#Player input for guess letter
guess_letter=str.lower(input('Enter your guess letter: '))
#Calling a sub function to check if correct letter was guessed
guess_check=guesscheck(guess_letter,answer_word,guess_no);
#Conditional: if incorrect letter
if guess_check == False:
guess_no +=1
print(answer_display)
#Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if x == guess_letter] #https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all]=guess_letter
print(answer_display)
#Conditional: if no remaining unknown letter then win screen
if answer_display.count('*')==0:
win = True
break
if win:
print("You won!")
else:
print("The correct answer was: ", answer_word)
print("You lost!")
To install random_words package in jupyter notebook.
run this command in code shell.
!pip install random_word
import package. from random_word import RandomWords
generate.
r = RandomWords()
print(r.get_random_word())
Code snippet:
import random
from random_word import RandomWords
# Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
while True:
try:
no_of_time = int(input("How many times do you want to play: "))
played_time = no_of_time
break
except ValueError:
print("Please enter a number. specify in number how many time you want to play.")
r=RandomWords()
scorecard = 0
# defining function
def guesscheck(guess, answer, guess_no):
if len(guess) == 1:
if guess in answer:
print("Correct, ", guess, " is a right letter")
return True
else:
print("Incorrect, ", guess, " is a not a correct letter. That was your chance number ", guess_no)
return False
else:
print("Enter only one letter")
while no_of_time:
while True:
try:
difficulty_level = int(input(
"Enter the difficulty you want to play: press [1] for easy, press [2] for medium, press [3] for hard, press [4] for manually word"))
if difficulty_level in [1, 2, 3, 4]:
break
else:
print("Enter number 1 or 2 or 3 or 4 not other than that!!")
continue
except ValueError:
print("Please enter difficulty level specific.")
answer_word = ""
if difficulty_level == 1:
while len(answer_word)!=5:
answer_word = r.get_random_word()
elif difficulty_level == 2:
while len(answer_word)!=6:
answer_word = r.get_random_word()
elif difficulty_level == 3:
while len(answer_word)!=10:
answer_word = r.get_random_word()
else:
answer_word=input("Enter manually what word you wanted to set..!")
win = False
# Storing the number of characters in different variable
answer_display = []
for each in answer_word:
answer_display += ["*"]
print(answer_display)
# initializing number of allowable guesses
guess_no = 1
while guess_no <= 5: # User chances given 5
# Player input for guess letter
guess_letter = str.lower(input('Enter your guess letter: '))
# Calling a sub function to check if correct letter was guessed
guess_check = guesscheck(guess_letter, answer_word, guess_no)
# Conditional: if incorrect letter
if guess_check == False:
guess_no += 1
print(answer_display)
# Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if
x == guess_letter] # https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all] = guess_letter
print(answer_display)
# Conditional: if no remaining unknown letter then win screen
if answer_display.count('*') == 0:
win = True
break
if win:
print("You won!")
scorecard += 1
else:
print("The correct answer was: ", answer_word)
print("You lost!")
no_of_time -= 1
print("You played " + str(played_time) + ":")
print("Won: " + str(scorecard) + " Guessed correctly!!")
print("Lose: " + str(played_time - scorecard) + "not Guessed correctly!!")
don't know why specific length is not working in random_word hence included while statement.. this code snippet is working you can go through this..!

How would I do a definition for a name validation

What I want to do:
I am trying to make a definition that takes an input (name as string) and checks if the name is in a set list.
If it is, the program will continue.
If it isn't, it will give the user 2 more chances to enter their name correctly.
Requirements:
I need to use the name variable after the definition.
I need the system to exit if the name is wrong 3 times.
Problems:
If the name is correct it works properly
However, if the name is wrong, it doesn't allow another name input, printing "You have 2 more tries" and "You have 1 more try" then ends the loop and exits.
Code:
names_allowed_to_play = ["MUM","DAD"]
def val_1 (name_1):
print("Player 1, you have 3 tries to enter the correct name")
print("")
a = 0
while a < 3:
name_1 = name_1.upper()
if name_1 in names_allowed_to_play:
print(name_1 + ", you are authorised to play, have fun!")
print("")
a = a + 4
names_allowed_to_play.remove(name_1)
elif name_1 not in names_allowed_to_play:
a = a + 1
if name_1 not in names_allowed_to_play and a ==1:
print("You have 2 more tries")
print("")
print("")
elif name_1 not in names_allowed_to_play and a ==2:
print("You have 1 more try")
print("")
print("")
if a == 3:
print("")
print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
sys.exit()
#Run definition
name_1 = input("Player 1, please enter your name to play: ")
val_1(name_1)
There are a few problems with your code:
you never ask the user for new input within the loop, instead just testing the first name again
you modify the (local) name_1 variable, but never return the value to the caller
you do not have to repeat all the conditions, and can use math to determine the number of tries remaining
You can try something like this:
def get_name(player, tries, names_allowed_to_play):
print(f"Player {player}, you have {tries} tries to enter the correct name")
for i in range(1, tries+1):
name = input("Please enter your name to play: ").upper()
if name in names_allowed_to_play:
print("You are authorised to play, have fun!")
names_allowed_to_play.remove(name)
return name
elif i < tries:
print(f"You have {tries - i} more tries")
else:
print("You messed up")
exit()
names_allowed_to_play = ["MUM","DAD"]
name1 = get_name(1, 3, names_allowed_to_play)
name2 = get_name(2, 3, names_allowed_to_play)
print(name1, name2)
This is working for me, I think the way you had structured it meant the logic was flawed.
import sys, time
names_allowed_to_play = ["MUM","DAD"]
def main():
authorised = False
attempts = 3
while authorised == False:
if attempts < 3:
print("You have",attempts,"remaining.")
if attempts > 0:
name = input("Player 1, please enter your name to play: ")
name = name.upper()
elif attempts <= 0:
print("You are locked out.")
time.sleep(1)
sys.exit()
if name in names_allowed_to_play:
print(name," you are authorised to play, have fun!")
names_allowed_to_play.remove(name)
authorised = True
else:
attempts -= 1
main()
Major changes:
put input() in while loop so you can get new input when the name is wrong, otherwise you only get the input once and the wrong name is checked by the if-statement 3 times
add return statement for allowed name so you can use the name later (such as print out or other functions)
You can find other minor changes in my code comment.
# change the names to lowercase so you don't need upper() for input
names_allowed_to_play = ["mum","dad"]
def player_validate():
# \n for new line, just works like your print("")
print("Player 1, you have 3 tries to enter the correct name\n")
tries = 0
while tries < 3:
player_name = input("Player 1, please enter your name to play: ")
if player_name in names_allowed_to_play:
print(player_name + ", you are authorised to play, have fun!\n")
names_allowed_to_play.remove(player_name)
# return will stop the loop so you don't need to break it by other code
return player_name
else:
tries = tries + 1
# use calculation instead of many elif statment
print(f"You have {3-tries} tries.")
# I have change Player 2 to Player 1, if it is not typo, you can change it back
print("Sorry Player 1, " + player_name + " ruined it! " + player_name + ", you are NOT AUTHORISED!")
# use exit() instead of sys.exit() or you will need to import sys at beginning
exit()
# Run function (I think function is a more common name then definition)
name_to_use_later = player_validate()
print(name_to_use_later)
I have fixed your code problem.
names_allowed_to_play = ["MUM", "DAD"]
def val_1():
print("Player 1, you have 3 tries to enter the correct name")
name_1 = input("enter your name")
a=0
while a < 3:
name_1 = name_1.upper()
if name_1 in names_allowed_to_play:
print(name_1 + ",you are authorised to play, have fun!")
a = a + 4
names_allowed_to_play.remove(name_1)
elif name_1 not in names_allowed_to_play:
a = a + 1
if name_1 not in names_allowed_to_play and a == 1:
print("You have 2 more tries")
name_1 = input("enter your name")
print("")
elif name_1 not in names_allowed_to_play and a == 2:
print("You have 1 more try")
name_1 = input("enter your name")
elifa == 3:
print("")
print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
exit()
val_1()

How to set a time limit for a game?

I've programmed a game that takes a song and artist name from an external file. The program prints the artist name but masks the title of the song, and the user must guess the title correctly to earn points. That works fine, but I want to add a time limit, so they only have 60secs to get the highest score they possibly can.
Here's the part of the code I'm referencing:
def pickSong_random():
score=0
lives=5
songFile = open("F_Songs.txt","r")
songList = songFile.readlines() #Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") #Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
#loop through
toDisplay += word[0] + " "
print(toDisplay)
#print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
while guesses <2:
guesses += 1
guess = input("[Guess]: ")
#Guess checking
if guess.lower() == artistAndSong[1].lower():
print("Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print ("(+3 points)")
print("\n")
score += 3
break
elif guesses == 2:
print ("(+1 point)")
print("\n")
score += 1
break
else:
print("That's incorrect, guess again.\n")
lives = lives-1
if lives == 0:
print ("You have no more lives to continue! Your score was:",score)
time.sleep(3)
slow_print ("Would you like to play again?")
playAgain = input("[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print ("Your last score was",score,", lets see if you can beat it this time...")
time.sleep(1)
print ("\n")
pickSong_random()
I've tried playing around with this concept, but no luck thus far:
import time
countdown=True
time=60
while countdown == True:
time = time-1
time.sleep(1.0)
print (time)
countdown=True
if time == 0:
print ("You've ran out of time!")
UPDATE 1
My projects code has now changed quite a far bit
#Casey_Neale
import sys
import random
import time
import math
import csv
import time, sys
newaccounts=True
loggedIn=False
yn=True
def tutorial(): #Games introduction
slow_print("Your aim is to get as many points as possible...")
print("\n")
time.sleep(1.5)
slow_print("You need to guess the name of each song to gain points...")
print("\n")
time.sleep(1.5)
slow_print("You have two guesses for each song...")
print("\n")
time.sleep(1.5)
slow_print ("The artist name is provided for you...")
time.sleep(0.5)
print("\n")
def slow_print(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.03)
def leaderboard():
print ("\n")
print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
f = open('H_Highscore.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
for i in leaderboard:
print(i)
f.close()
time.sleep(10)
sys.exit()
def loginsys():
doublecheck=True
while doublecheck == True:
verifyRegister = input ("➡Welcome | Are you a registered user?\n[Y/N]: ")
print (" ")
if verifyRegister == "n" or verifyRegister == "N": #If the user is not already registered
if newaccounts == True:
loop=True
while loop == True:
username = input ("Please enter a username\n[User]: ")#Prompts the user to provide a desired username
print (" ")#Prompts for username
checkusername = input ("Please retype your username\n[Verify]: ")#Verifys username
print (" ")#Prompts to verify username
if checkusername != username:
print ("Invalid, please try again")
loop=True
else:
loop=False
time.sleep(0.5)
passloop=True
while passloop == True:
password = input ("Please enter a password\n[Password]: ") #Prompts the user to provide a desired password
print (" ")#Prompts for password
checkpassword = input ("Please retype your password\n[Verify]: ") #Verifys password
print (" ")#Prompts to verify password
if checkpassword != password:
print ("Invalid, please try again")
print (" ")
passloop=True
else:
passloop=False
file = open("C_AccountData.txt","a") #Opens the file C_AccountData.txt in write mode/opens connection
file.write("USRN:") #Prefix Username to make the file easier to read
file.write(username) #Writes the username
file.write("|") #Partition for visual ease to make the file easier to read
file.write("PSWD:") #Prefix Password to make the file easier to read
file.write(password)#Writes the password
file.write("\n") #New line to make the file easier to read
file.close() #Closes file/ends connection
print ("✓Your account has been created") #Verifies that the account has been made to the user
time.sleep(2)
print ("\n")
doublecheck=True #Loop
if verifyRegister == "Y" or verifyRegister == "y":
loop=True
if loop == True:
user = input("[User]: ")
passw = input("[Password]: ")
f = open("C_AccountData.txt", "r")
for line in f.readlines():
uspwd = line.split("|")
us = uspwd[0]
pw = uspwd[1]
if (user in us) and (passw in pw):
loop=False
print("Login successful, welcome",user)
doublecheck=False
else:
if loop == True:
print ("\n")
print ("Sorry, your account details were not recognised. ")
else:
if verifyRegister != "Y" or verifyRegister != "y" or verifyRegister != "N" or verifyRegister != "n" or verifyRegister !="backup":
print("\n")
doublecheck=True
def pickSong_random():
score=0
lives=5
songFile = open("F_Songs.txt","r")
songList = songFile.readlines() #Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") #Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
#loop through
toDisplay += word[0] + " "
print(toDisplay)
#print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
while guesses <2:
guesses += 1
guess = input("[Enter your guess]: ")
#Guess checking
if guess.lower() == artistAndSong[1].lower():
print("✓Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print ("\n")
print ("⬆(+3 points)⬆")
print("\n")
score += 3
break
elif guesses == 2:
print ("\n")
print ("⬆(+1 point)⬆")
print("\n")
score += 1
break
else:
print("❌The song name isn't",guess,"\n")
lives = lives-1
if guesses == 2:
print ("Sorry, you couldn't guess the song.")
print ("\n")
if lives == 0:
print ("You have no more lives to continue! Your score was:",score)
time.sleep(3)
print("\n")
slow_print ("Would you like to play again?")
playAgain = input("\n[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
print ("\n")
user = str(input("Enter a name to save your highscore: ")) #user variable is not saved from the login system as it is defined as a function separately
file = open ("H_Highscore.txt","a")
file.write(user)
file.write(",")
file.write(str(score)) #(int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard()
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print ("Your last score was",score,", lets see if you can beat it this time...")
time.sleep(1)
print ("\n")
pickSong_random()
loginsys() #LOGIN PROTOCOL
time.sleep(3)
print("\n")
tutorial() #TUTORIAL PROTOCOL
slow_print ("Prepare yourself! The game will begin in...\n")
time.sleep(0.5)
print("\n")
slow_print("5...")
time.sleep(0.5)
print("\n")
slow_print("4...")
time.sleep(0.5)
print("\n")
slow_print ("3...")
time.sleep(0.5)
print("\n")
slow_print ("2...")
time.sleep(0.5)
print("\n")
slow_print ("1...")
time.sleep(0.5)
print("\n")
pickSong_random() #GAME PROTOCOL
sys.exit() #EXIT PROTOCOL
Here's how to do it with the threading.Timer() class I suggested in a comment. These can be configured to delay a specified amount of time and the call as function of your choosing.
In the code below I've defined a callback function named timeout() and a global variable named time_ran_out that it sets to True when the timer expires. There's comments in the added code describing what's being done. All the callback function does is set the value of a variable. Other code in the pickSong_random() function checks the value of this variable to determine if the callback function got called or not.
The nice thing about Timer instances (and functions they callback) is that their execution occurs in the background, in parallel with the the main thread which is running the game itself—so using them doesn't impact game's execution or code very much.
Note I also reformatted your code so it follows PEP 8 - Style Guide for Python Code guides so it's a lot more readable (and easier to work on) in my opinion.
import random
import sys
import time
from threading import Timer
TIMELIMIT = 10.0 # Seconds (set low for testing).
def slow_print(s):
for c in s:
sys.stdout.write('%s' % c)
sys.stdout.flush()
time.sleep(0.03)
def pickSong_random():
# Local Timer callback function.
def timeout():
nonlocal time_ran_out # Reference variable defined in enclosing scope
# (so a local one isn't created automatically).
time_ran_out = True
score = 0
lives = 5
songFile = open("F_Songs.txt", "r")
songList = songFile.readlines() # Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") # Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
# loop through
toDisplay += word[0] + " "
print(toDisplay)
# print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
timer = Timer(TIMELIMIT, timeout) # Create a timer thread object.
time_ran_out = False # Define local variable the callback function modifies.
timer.start() # Start the background timer.
while guesses < 2:
if time_ran_out:
print('Times up!')
break
guesses += 1
guess = input("[Enter your guess]: ")
# Guess checking
if guess.lower() == artistAndSong[1].lower():
print("✓Correct! The song was " + artistAndSong[1]
+ " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print("\n")
print("↑(+3 points)↑")
print("\n")
score += 3
break
elif guesses == 2:
print("\n")
print("↑(+1 point)↑")
print("\n")
score += 1
break
else:
print("╳The song name isn't", guess, "\n")
lives = lives-1
if guesses == 2:
print("Sorry, you couldn't guess the song.")
print("\n")
if lives == 0:
print("You have no more lives to continue! Your score was:", score)
time.sleep(3)
print("\n")
slow_print("Would you like to play again?")
playAgain = input("\n[Y/N]: ")
if playAgain == ("n") or playAgain == ("N"):
print("\n")
# user variable is not saved from the login system as it is
# defined as a function separately
user = str(input("Enter a name to save your highscore: "))
file = open ("H_Highscore.txt", "a")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard()
sys.exit()
if playAgain == ("Y") or playAgain == ("y"):
print("Your last score was", score,", lets see if you can beat it this time...")
time.sleep(1)
print("\n")
pickSong_random()
if __name__ == '__main__':
pickSong_random()
Simply record the start time, and break from your loop if the time is up. By sleeping you make your program hibernate and the user can not do anything. So "fasteness" does not make any difference because you can't do anything while the program sleeps:
import random
import datetime
correct = 0
start = datetime.datetime.now()
while True:
print("Math test. Add , dont screw up, you got {}s left".
format(20-(datetime.datetime.now()-start).seconds))
a,b = random.choices(range(1,20),k=2)
c = input(" {:>2} + {:>2} = ".format(a,b))
if (datetime.datetime.now()-start).seconds > 20:
print("Times up. Score: {}".format(correct))
break
try:
if a+b == int(c):
correct += 1
print("Correct")
else:
print("Wrong")
except:
print("Wrong")
Output:
Math test. Add , dont screw up, you got 20s left
17 + 8 = 23
Wrong
Math test. Add , dont screw up, you got 18s left
10 + 2 = 12
Correct
Math test. Add , dont screw up, you got 14s left
1 + 7 = 8
Correct
Math test. Add , dont screw up, you got 12s left
5 + 19 = 24
Correct
Math test. Add , dont screw up, you got 8s left
4 + 3 = 7
Correct
Math test. Add , dont screw up, you got 5s left
3 + 18 = 21
Correct
Math test. Add , dont screw up, you got 3s left
15 + 12 = 27
Correct
Math test. Add , dont screw up, you got 1s left
7 + 8 = 15
Times up. Score: 6
It turns out you were actually reassigning the "time" module to an integer of 60, overwriting the library, which is why it had no attribute ".sleep()". Also the countdown part is irrelevant and a bit redundant. Anyways, this revised bit of code worked for me:
import time
sec=60
while sec != 0:
print(sec)
sec = sec-1
time.sleep(1)
print ("You've ran out of time!")
Hope this helps!
While Om Agarwal may have a possible solution, you may also want to consider using a non-blocking approach in your game using the built-in pygame time.
start_ticks = pygame.time.get_ticks()
while guesses < 2:
# OTHER GAME CODE HERE
seconds = (pygame.time.get_ticks() - start_ticks) / 1000
if seconds > 60:
print ("You've ran out of time!")
break
Cheers!
Edit 1: Added example modification.
import pygame
import time
import random
import sys
def pickSong_random():
score = 0
lives = 5
songFile = open("F_Songs.txt", "r")
songList = songFile.readlines() # Reads from the bridged file
songFile.close()
while True:
chosenSong = random.choice(songList)
chosenSong = chosenSong.strip("\n")
artistAndSong = chosenSong.split(":") # Defines song split
toDisplay = ""
toDisplay += artistAndSong[0] + ": "
songTitleWords = artistAndSong[1].split(" ")
for word in songTitleWords:
# loop through
toDisplay += word[0] + " "
print(toDisplay)
# print("2" +toDisplay)
toDisplay = toDisplay.strip("None")
guesses = 0
start_ticks = pygame.time.get_ticks()
while guesses < 2:
guesses += 1
guess = input("[Guess]: ")
seconds = (pygame.time.get_ticks() - start_ticks) / 1000
if seconds > 60:
print("You've ran out of time!")
break
# Guess checking
if guess.lower() == artistAndSong[1].lower():
print("Correct! The song was " + artistAndSong[1] + " by " + artistAndSong[0])
print("It took you", guesses, "guess(es)!")
if guesses == 1:
print("(+3 points)")
print("\n")
score += 3
break
elif guesses == 2:
print("(+1 point)")
print("\n")
score += 1
break
else:
print("That's incorrect, guess again.\n")
lives = lives - 1
if lives == 0:
print("You have no more lives to continue! Your score was:", score)
time.sleep(3)
slow_print("Would you like to play again?")
playAgain = input("[Y/N]: ")
if playAgain == "n" or playAgain == "N":
sys.exit()
if playAgain == "Y" or playAgain == "y":
print("Your last score was", score, ", lets see if you can beat it this time...")
time.sleep(1)
print("\n")
pickSong_random()

Error: variable referenced before assignment

import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
return
play()
From the information available for now, I would say that this is because you did not assign any value for
questions
variable
To solve this, simply add
questions = 10 # or other value you may want
at the very start of the play() function
You need to initialize questions variable to 0 before while loop and also initialize counters variable to 0 and return statement should be outside while loop.
Below is the corrected code
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
#initialization
questions,counter =0,0
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
# return outside while loop
return
play()
An example for you:
#!/usr/bin/env python3.6
import time
from random import randrange
def play():
counter = 0
for i in range(10):
num1 = randrange(9, 17)
num2 = randrange(6, 17)
print(f"What does {num1} x {num2} = ")
guess = input("Your guess?: ")
answer = str(num1 * num2)
if guess == answer:
print("Correct\n")
counter += 1
else:
print("Your answer was Wrong")
print(f"The real answer was {answer}\n")
time.sleep(0.5)
print("You got " + str(counter) + " out of 10")
def main():
print(
"Welcome to the Game\n"
"You must complete the next 10 Multiplication Questions "
"to be truly ready for the challenges of life\n"
)
choice = input("Are you ready? Y / N: ")
if choice.upper() == "N":
return
print()
play()
if __name__ == "__main__":
main()

How to limit time user takes to input - Python

EDIT:
I solved this by implementing #L3viathan's solution. Here is the updated code:
import operator
import random
from time import time
import sys
def menu():
menu = input("\n\n\n--------\n Menu \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
if menu == "1":
play_game()
if menu == "2":
print("Exiting...")
sys.exit()
while menu != "1" or menu != "2":
print("Please enter a valid choice")
menu = input("--------\n Menu \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
if menu == "1":
play_game()
if menu == "2":
print("Exiting...")
break
def game_over():
print("Game over.")
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
def play_game():
print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
counter = 1
score = 0
while counter == 1:
ops = {"+":operator.add,
"-":operator.sub,
"x":operator.mul}
num1 = random.randint(0, 10)
op = random.choice(list(ops.keys()))
num2 = random.randint(1, 10)
print("\nWhat is {} {} {}? ".format(num1, op, num2))
start = time()
guess = float(input("Enter your answer: "))
stop = time()
answer = ops.get(op)(num1,num2)
if guess == answer:
if stop - start > 3:
print("You took too long to answer that question. (" + str(stop - start) + " seconds)")
def game_over():
print("Game over.")
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
menu()
game_over()
break
else:
score = score + 1
print("Correct!\nScore: " + str(score))
else:
print("Game over.")
counter = counter - 1
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
if counter != 1:
menu()
menu()
Thank you all for your contributions.
------ EDIT END -------
I have been searching Stack Overflow for a solution however I could not find anything which works with my game, therefore I appologise if this is a duplicate question.
I am making a math game where a user has to answer a simple arithmetic question, each time the user enters the correct answer, the score increases by one. However, if the user enters a wrong answer, the game ends.
I would like to add a timeout feature to the game, for example when a user is entering an answer to one of the questions, if the user takes more than 3 seconds to answer, the game ends. Does anyone know how to do this?
All of the solutions I could find were for Unix, not Windows.
Here is my code:
import operator
import random
def play_game():
print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
counter = 1
score = 0
while counter == 1:
ops = {"+":operator.add,
"-":operator.sub,
"x":operator.mul}
num1 = random.randint(0, 10)
op = random.choice(list(ops.keys()))
num2 = random.randint(1, 10)
print("\nWhat is {} {} {}? ".format(num1, op, num2))
guess = float(input("Enter your answer: "))
answer = ops.get(op)(num1,num2)
if guess == answer:
score = score + 1
print("Correct!\nScore: " + str(score))
else:
print("Game over.")
counter = counter - 1
file = open("score.txt", "r")
highscore = file.read()
if int(highscore) < score:
file = open("score.txt", "w")
file.write(score)
file.close()
print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
else:
print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
if counter != 1:
menu = input("\n\n\nMenu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
if menu == "1":
play_game()
elif menu == "2":
print("Exiting...")
break
while menu != "1" or menu != "2":
print("Please enter a valid choice")
menu = input("Menu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
if menu == "1":
play_game()
elif menu == "2":
break
print("Exiting...")
play_game()
The easiest way to do this would be to time the call to input:
from time import time
start = time()
answer = input("Answer this in 3 seconds: 1 + 1 = ")
stop = time()
if stop - start < 3:
if answer == "2":
print("Correct!")
else:
print("Wrong!")
else:
print("Too slow")
This way is simple, but you couldn't abort the user's ability to input after three seconds, only wait for it and then see if it was fast enough.

Categories