Input from the use in a try/except block - python

List item
i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks
Sloved!!
import sys
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:
if difficulty == '1':
print('Easy game mode is set!')
elif difficulty =='2':
print('Hard game mode is set!')
elif difficulty =='quit':
print('Sheeeeeeeeeeeeeeesh')
except:
continue
if difficulty == '1' or difficulty =='2':
break
elif difficulty == 'quit':
sys.exit('byeeeee')
break
#elif difficulty
else:
print('invalid ')

You are storing the user input in uppercase for difficulty variable.
And in if condition verifying in lowercase.
So remove the upper() from
input("Choose difficulty 1 for easy 2 for hard: ").upper()

try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
It breaks the loop when the correct input is given, and keeps looping otherwise.
If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
raise ValueError #notice the additional line here

Related

yes/no loop not working properly when i used OR keyword [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 months ago.
I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program
when i use this code it works but when i use if a=='yes' or 'Yes' and elif a=='no' or 'No' in the somehow the output shows the print statement of the if statement even when i enter no.
My program without the OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes':
print("enter the program")
elif a=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
My initial program with OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes' or 'Yes':
print("enter the program")
elif a=='no' or 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
In an or statement you have to compare a with the value in all expressions:
while True:
a = input("Enter yes/no to continue")
if a == 'yes' or a == 'Yes':
print("enter the program")
elif a == 'no' or a == 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
A more pythonic way is to use .lower() in your case. For example:
a == 'yes' or a == 'Yes' # is equeal to:
a.lower() == 'yes'
You have a few options:
while True:
a = input("Enter yes/no to continue")
if a.lower()=='yes':
print("enter the program")
elif a.lower()=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
or you can do this:
while True:
a = input("Enter yes/no to continue")
if a=='yes' or a=='Yes':
print("enter the program")
elif a=='no' or a=='No':
print("EXIT")
break
else:
print("Enter either yes/no")
When you use or, you should write complete condition again.
Here if you want to check a=="Yes" also, you should declare it completely.
if a == 'yes' or a == 'Yes':
...
You can also use this:
if a.lower() == 'yes'
...

Trying to link my user name input and menu to my game function in python hangman

I'm trying to link my ask_for_name() and menu() functions to my play() function but where
ever I place the function headings it doesn't seem to work or get called. The game starts up first and at the end of gameplay asks if you want to restart, yes or no, If you click no, it goes back to what I want at the beginning of my game, my user-input asking for name and the menu, press 1 to play the game and 2 for instructions. When I click 1 the game wont start and throws an error message, does anyone know what I'm missing here? I'm new to python and seem to keep going in circles with this problem, the code is mentioned below:
def ask_for_name():
while True:
name = input(YELLOW_COLOR + "Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
return name
def menu():
"""
menu function which gives the user two options
- Press 1 to play or 2 for instructions
- only accepts valid keys or error message comes up
"""
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
play()
elif user_input == "I":
print(
"1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
menu()
else:
print(RED_COLOR + "Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
def check_letter(letter, word):
global reveal
for i in range(0,len(word)):
letter = word[i]
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game():
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?"
"Y/N").upper()
try:
if restart == "Y":
game_restart = True
play()
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
menu()
else:
raise ValueError(
"You must type in Y or N"
)
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
player_lost()
print(f"YOU FAILED the word was: {word}")
restart_game()
Since there were portions of the game program missing, I filled in the missing bits with some placeholder functions. After trying out the game and seeing where it appeared to get stuck, I made some tweaks to it to make it function in the spirit of a hangman game. Following is the tweaked code for your analysis.
import os
word = "dog" #random.choice(WORDS)
word = word.upper()
reveal = list(len(word)*'_')
lives = 8
game_is_won = False
hangman = [] # Added this so as to make the game work - temporary
for g in range(0,8):
hangman.append('-')
def header():
return
def ask_for_name():
while True:
name = input("Please Enter Your Name:\n")
if not name.isalpha():
print("Name must be letters only\n")
else:
print(f"Hello {name}, Welcome to Chris's Hangman and Good Luck!\n")
menu()
break # Added this to get out of the while loop
return name
def menu():
while True:
user_input = input("Press P to Play game\nPress I for Instructions\n").upper()
if user_input == "P":
lives = 8
game_is_won = False
break
elif user_input == "I":
print("1.The computer will generate a random word and it's\n"
"your task to guess the letters from the word.\n"
"2.To guess, type a letter of your choice and hit enter.\n"
"3.If you guess correctly, the letter will be revealed.\n"
"4.If you guess incorrectly, you will lose a life and \n"
" the Hangman will start to appear.\n"
"5.You have 8 lives to guess the correct word.\n"
"Good Luck!\n")
enter_input = input("Press Enter to go back to the menu\n").upper()
if enter_input == "":
pass
#menu()
else:
print("Oops look's like you pressed the wrong key!\n")
else:
print("Invalid Character, please try again!\n")
def check_letter(guess, word):
global reveal
for i in range(0,len(word)):
letter = str(word[i])
if guess == letter:
reveal[i] = guess
if '_' not in reveal:
return True
else:
return False
def restart_game(): # Added return of decision
"""
Gives player option to restart, otherwise returns to menu
"""
game_restart = False
while not game_restart:
restart = input("Would you like to play again?" "Y/N/Q ").upper() # Added a quit option
try:
if restart == "Y":
return True
elif restart == "N":
game_restart = True
print("\n")
header()
ask_for_name()
#menu()
return True
elif restart == "Q":
return False
else:
raise ValueError("You must type in Y or N")
except ValueError as e:
print("\n You must type in Y or N Please try again.\n")
def player_won(): # Added this to make the game work
print("Yea!")
return
def player_lost(): # Added this to make the game work
print("Boohoo")
return
def play():
os.system("clear")
header()
print(hangman[8-lives])
print(' '.join([str(e) for e in reveal]))
print(f"You have {lives} lives")
header()
ask_for_name()
while game_is_won == False and lives > 0:
play()
guess = input('Guess a letter or an entire word:')
guess = guess.upper()
if guess == word:
game_is_won = True
reveal = word
elif len(guess) == 1 and guess in word:
game_is_won = check_letter(guess, word)
else:
lives -= 1
if game_is_won:
player_won()
print("WELL DONE")
else:
if lives <= 0:
player_lost()
print(f"YOU FAILED the word was: {word}")
if game_is_won == True or lives <=0: # Conditioned restart
if restart_game() == True:
game_is_won = False
lives = 8
reveal = list(len(word)*'_')
The key bits were adjusting some of the "if" tests to allow for life decrements, prompting for a name, prompting the menu, and restarts.
Here is a quick sample at the terminal.
-
_ _ _
You have 8 lives
Guess a letter or an entire word:Dog
Yea!
WELL DONE
Would you like to play again?Y/N/Q Q
Give those a try.

Using a while loop with try catch python

I'm trying to catch an invalid input by the user in this function when the user runs the program. The idea is to use a try,exception block with a while loop to ensure that the code is continuously run until a valid input is made by the user, which is 1-5.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
raise Exception ("Invalid input")
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
I would advise against using exceptions for controlling flows.
Instead, I would keep iterating until the value is correct and use a return statement to indicate I'm done.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
continue
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
return

Go to a specific raw_input()?

So I'm trying to figure out how I can make this simple little program to go back to the raw_input if the user inputs something else then "yes" or "no".
a = raw_input("test: ")
while True:
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
This is what I got so far, I'm new and it's hard to understand. Thanks in advance.
As #DavidG mentioned, just add your raw_input statement in loop:
while True:
a = raw_input("Enter: ")
if a == "yes":
print("You have entered Yes")
break
elif a == "no":
print("You have entered No")
break
else:
print("yes or no idiot")
Simply you can put the first instruction inside the loop; in this way, every time the user inserts a value different to yes or no you can print a message and wait to a new input.
while True:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
Describe a condition checker for while and read input everytime when your condition is not meet. Inline returns are good for low quantity conditions but when your choice count is too much or condition in condition situations appear, inline returns are becoming trouble.
Thats why you must use condition checkers(like cloop) instead of inline returns.
cloop=True
while cloop:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
cloop=False
elif a == "no":
print("nonono")
cloop=False
else:
print("yes or no idiot")
cloop=True

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

Categories

Resources