How would I do a definition for a name validation - python

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

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..!

Repeated prints from loop

I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")

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

append variable values to specific folder/file

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.

Restarting a Python Program

I know this has been asked before, but I haven't understood the answer.
My code is this:
# Code by Jake Stringer
# 2014
import os
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
input("Please press enter to continue.")
os.system('CLS')
print("Hailstone Numbers:")
print("")
print("RULE 1: Start with any number.")
print("If it is even > divide it by 2.")
print("If it is odd > multiply it by 3, then add 1")
print("")
print("RULE 2: Keep going")
print("")
print("RULE 3: You will always end up at 1.")
print("")
print ("Let's put Hailstone Numbers into action.")
print("")
user = int(input("Please enter any number: "))
print("")
os.system('CLS')
print (user)
print("")
if user % 2 == 0 :
print("What you entered is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("What you entered is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
input("Please press enter to continue.")
os.system('CLS')
print("According to RULE 2, we need to keep on going.")
while user > 1:
thing3 = "We are currently on the number " + str(user) + "."
print (thing3)
if user % 2 == 0 :
print("This number is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("This number is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
print("Now we will continue.")
input("Please press the enter key.")
os.system('CLS')
print("")
print(user)
print("")
print("As you can see, you have ended up on the number 1.")
print("")
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
restart = input("Would you like a try the program again??")
if restart == "yes":
# restart code here!
else:
# quit the program!
.... So, how do I make the program restart? I have seen in past answers to use some code that when I tried out, says that "sys" isn't defined (so I'm guessing it doesn't exist). It should also be noted that I'm a beginner at Python. Thanks for any help!!
Stick the whole thing in a function and then put a repeat-loop outside the function.
import os
def my_function():
print(" Hailstone Numbers ")
print("")
# more code here
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
while True:
my_function()
restart = input("Would you like a try the program again??")
if restart == "yes":
continue
else:
break
You might want to head over to Code Review and get some folks to look over your code, by the way.
You can put it in a loop as follows:
# Code by Jake Stringer
# 2014
import os
restart = 'yes'
while restart in ('yes', 'Yes', 'y', 'Y'):
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
input("Please press enter to continue.")
os.system('CLS')
print("Hailstone Numbers:")
print("")
print("RULE 1: Start with any number.")
print("If it is even > divide it by 2.")
print("If it is odd > multiply it by 3, then add 1")
print("")
print("RULE 2: Keep going")
print("")
print("RULE 3: You will always end up at 1.")
print("")
print ("Let's put Hailstone Numbers into action.")
print("")
user = int(input("Please enter any number: "))
print("")
os.system('CLS')
print (user)
print("")
if user % 2 == 0 :
print("What you entered is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("What you entered is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
input("Please press enter to continue.")
os.system('CLS')
print("According to RULE 2, we need to keep on going.")
while user > 1:
thing3 = "We are currently on the number " + str(user) + "."
print (thing3)
if user % 2 == 0 :
print("This number is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("This number is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
print("Now we will continue.")
input("Please press the enter key.")
os.system('CLS')
print("")
print(user)
print("")
print("As you can see, you have ended up on the number 1.")
print("")
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
restart = input("Would you like a try the program again??")

Categories