I would like to make it so my menu works in a way which if a letter is input or anything other than a correct answer is input my script doesn't just end abruptly and it asks to input a correct option. Could anyone help me do this please? Here is the code i have so far:
#variables for password entry
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
#password entry code
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("out of guesses!")
else:
print("You are into the secret lair!")
#Menu code
def menu(menu):
print("--------------------------\nMenu\n--------------------------\n1.Secret
Sauce\n2.More secret stuff\n3.Even more secret stuff\n4.Exit")
choice = int(input("--------------------------\nENTER CHOICE: "))
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4:
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
#exit loop for the def
running = True
while running:
menuChoice = menu(menu)
if menuChoice == False:
print("\nGoodbye")
running = False
Instead of
choice = int(input("--------------------------\nENTER CHOICE: "))
You can do the following:
choice = input("--------------------------\nENTER CHOICE: ")
and then after it we need to check if the string is a digit, so you can transfer it to "int" type safely.
if choice.isdigit():
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4 or choice != (1,2,3,4):
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
In your menu() function,
Instead of immediately casting the input into an int, you can use a try statement to make sure the input is an integer, so if the user types in a letter your program will not stop. For example:
validInput = False
while validInput == False:
choice = input("--------------------------\nENTER CHOICE: ")
try:
choice = int(choice)
validInput = True
except:
print("Please enter an integer.")
Replace choice = int(input("--------------------------\nENTER CHOICE: ")) with the above code and it will work.
Related
from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break
It is a number guessing game
Explanation
At first it asks the user to enter a number between 1 to 50
Then if the number is correct then you win else you have to try again (The winning number is random offcourse)You also have limited guesses
The problem is mentioned below the code
Here is my code:)
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = False
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
The problem is when the game ends
It asks whether we want to play again
But if we type "Yes" it again asks the same "Do you want to play again"
However typing "No" works fine and the program ends
you have to set game_over = False in case ask1 = yes so that it can come out of the parent while loop and proceed. Also, you'll have to reset number of guesses etc so that it starts as a new game.
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
You toggle game_over incorrectly, it should be set to True, not to False if the answer to replay is yes.
while not end_game: # End game must be false to replay
while not number_enter:
#... ask number
while not game_over: # But Game_over should be True to stop asking to replay
#... Check number good
#... Ask to replay
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True # <<<< Thats the problematic part, it must be True
# in your code it is False, So it result in
# an "infinite" loop, if yes.
break
I dont understand why the following while loop wont end? The following code just keeps endlessly asking for the user input. It should be a simple function that flips a coin and then returns whether the user guess correctly or not.. as far as I can tell the boolean expressions in the while statement are ok.
Appreciate any feedback and sorry id advance if the format isnt correct..
import random
def coin_flip():
random_choice = random.randint(1,2)
user_input = ""
if random_choice == 1:
random_choice = "Heads"
else:
random_choice = "Tails"
while user_input != "Heads" or user_input != "Tails":
user_input = input("Heads or Tails?")
if user_input == random_choice:
print("Congratulations!", "The result was", random_choice, " and you guess correctly!")
else:
print("Bad luck!", "The result was", random_choice, " and you guessed incorrectly.")
First of all your condition is correct however you need to indent correctly. I am assuming it should loop continuously until the user guesses the right answer break. Check the code below
import random
def coin_flip():
random_choice = random.randint(1,2)
if random_choice == 1:
random_choice = "Heads"
else:
random_choice = "Tails"
user_input = ""
while True:
user_input = input("Heads or Tails?")
if user_input == random_choice:
print("Congratulations!", "The result was", random_choice, " and you guess correctly!")
break;
else:
print("Bad luck!", "The result was", random_choice, " and you guessed incorrectly.")
Your problem is in the or condition:
while user_input != "Heads" or user_input != "Tails":
The user input may be "Heads", in which case user_input != "Tails". It may instead be "Tails", in which case user_input != "Heads".
You could simply use an and, but the most Pythonic way to approach this would be:
while user_input not in ("Heads", "Tails"):
Hope that helps.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")
The Code is working, but after 2 trys of the code it will just stop, this is in the section of playagain() when im asking the yes or no question it will display the error but will stop after the trys am i doing it wrong?
import random
import time
import getpass
import sys
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
return playagain()
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
return playagain()
else:
print("This is Invalid, Please Provide a 3 Digit Code")
#This is the Section just for Reference
def playagain():
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
return
Here's a cleaned-up version:
from random import randint
from time import sleep
DELAY = 0.5
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
# not an int, try again
pass
def get_yn(prompt):
while True:
yn = input(prompt).strip().lower()
if yn in {"y", "yes"}:
return True
elif yn in {"n", "no"}:
return False
def game(tries=100):
code = get_int("Please enter a 3-digit number (ie 091): ", 0, 999)
lo, hi = 0, 999
for attempt in range(1, tries+1):
sleep(DELAY)
guess = randint(lo, hi)
if guess < code:
print("Guessed {:03d} (too low!)".format(guess))
lo = guess + 1
elif guess > code:
print("Guessed {:03d} (too high!)".format(guess))
hi = guess - 1
else:
print("{:03d} was correct! The prisoner escaped on attempt {}.".format(guess, attempt))
return True
print("The prisoner failed to escape!")
return False
def main():
while True:
game()
if get_yn("Do you want to play again? "):
print("You chose to play again.")
else:
print("Alright, bye!")
break
if __name__=="__main__":
main()
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
x = False
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
x = False
else:
print("This is Invalid, Please Provide a 3 Digit Code")
playagain()
#This is the Section just for Reference
def playagain():
playagain = ""
while (playagain != "yes" or playagain != "no"):
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
game1()
See https://repl.it/B7uf/3 for a working example.
Games typically run in a game loop which you have implemented using while x = True. The gameloops exits when the game is over and then user is asked to restart it. The bugs you were experiencing were due to the gameloop prematurely exiting before the user could be asked to restart.
The code below above that problem. There are other things that could be updated to improve the flow, but will leave that to you.
Use try/catch blocks instead of boolean checks
Break the game loop out into a separate method