How to control users input if not 'y' or 'n' - python

I am new to Python and taking a class for it.
I am making a 'choose your own story' game where users put either 'y' or 'n' to lead to another situation.
Here is part of what I have:
print("Do you want to open the door")
if input() == "y":
print("You opened the door. It is a mostly empty room but you spot something in the corner")
elif input() == "n":
print("You decided not to enter the room, you move down the hallway")
if input() != "y" or "n":
print("Please put y or n")

For one, you'll want only one input() call, and you'll need to store the response in a variable.
Then, you'll need a loop in case to repeat the prompt in case they give an incorrect reply:
while True:
response = input("Do you want to open the door?")
if response == "y":
print("You opened the door. It is a mostly empty room but you spot something in the corner")
break
elif response == "n":
print("You decided not to enter the room, you move down the hallway")
break
print("Please put y or n")
Then, foreseeing there will be many more of this kind of prompt in your game, we can wrap this in a function that returns True or False. (I took the opportunity of also adding lower-casing, so either Y or y (or N/n) work.)
def prompt_yes_no(question):
while True:
response = input(question).lower()
if response == "y":
return True
elif response == "n":
return False
print("Please put y or n")
if prompt_yes_no("Do you want to open the door?"):
print("You opened the door. It is a mostly empty room but you spot something in the corner")
else:
print("You decided not to enter the room, you move down the hallway")

To compare your input with "y" and "n", you should set a variable to store the input.
print("Do you want to open the door")
x=input()
if x == "y":
print("You opened the door. It is a mostly empty room but you spot something in the corner")
elif x == "n":
print("You decided not to enter the room, you move down the hallway")
else:
print("Please put y or n")

Related

Python while not true loops

door = input("Do you want to open the door? Enter yes or no: ").lower()
while door != "yes" and door != "no":
print("Invalid answer.")
door = input("Do you want to open the door? Enter yes or no: ").lower()
if door == "yes":
print("You try to twist open the doorknob but it is locked.")
elif door == "no":
print("You decide not to open the door.")
Is there an easier way to use the while loop for invalid answers? So I won't need to add that line after every single question in the program.
I tried def() and while true, but not quite sure how to use the them correctly.
One way to avoid the extra line:
while True
door = input("Do you want to open the door? Enter yes or no: ").lower()
if door in ("yes", "no"):
break
print("Invalid answer.")
Or if you do this a lot make a helper function.
def get_input(prompt, error, choices):
while True:
answer = input(f"{prompt} Enter {', '.join(choices)}: ")
if answer in choices:
return answer
print(error)
Example usage:
door = get_input("Do you want to open the door?", "Invalid answer.", ("yes", "no"))
if door == "yes":
print("You try to twist open the doorknob but it is locked.")
else:
print("You decide not to open the door.")
while True:
answer = ("Enter yes or no: ").lower()
if answer in ["yes", "no"]:
break
print("Invalid answer.")
# loop will repeat again

Validate User Input I don't want it to start over when I say no after putting in the wrong input

I am trying to validate a users input by using while True:
When I type the wrong input it tells the user invalid, but when I say no I don't want to continue the code still start's over when I want it to exit the program. How would I fix this?
Output text to the console
def play_again():
print("")
incorrect = ""
while incorrect != "yes" and incorrect != "no":
incorrect = input("Not a valid entry.\n"
"Please choose yes or no:\n").lower()
if "y" in incorrect:
break
elif "n" in incorrect:
break
return incorrect
while True:
print("")
intro()
# Output text to the console
print("")
make_choice()
accept = input("would you like to play again? \n"
"Type yes or no: ").lower()
if 'n' in accept:
print_pause("Thanks for playing!")
break
elif 'y' in accept:
print_pause("Awsome! Lets play again.")
else:
play_again()
All of the logic should be in the play_again function. It can return True if the user wants to play again, else False.
def play_again():
accept = input("would you like to play again?\nType yes or no: ").lower()
while True:
if accept in ["y", "yes"]:
print_pause("Awesome! Lets play again.")
return True
elif accept in ["n", "no"]:
print_pause("Thanks for playing!")
return False
accept = input("Not a valid entry.\nPlease choose yes or no:\n").lower()
while True:
print("")
intro()
print("")
make_choice()
if not play_again():
break

How to restrict useer input with a yes or no question python

I have am making a game in which it asks a user to answer a question. The question is a yes or no question:
print("Lying on the ground next to you is a stone slab.")
pick = input("Do you pick up the slab? Yes/No ")
print(" ")
if pick=="yes":
print("You pick up the slab and begin reading.")
elif pick=="no":
print("You walk forwards and land facefirst onto the slab.")
elif pick=="Yes":
print("You pick up the slab and begin reading.")
elif pick=="No":
print("You walk forwards and fall facefirst onto the slab")
print(" ")
I have this but I need to make it so that the user cant input anything other than yes or no.
Use a while loop. Break out of the loop when they type a valid response, otherwise repeat.
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No ").lower()
if pick == 'yes':
print("You pick up the slab and begin reading.")
break
elif pick == 'no':
print("You walk forwards and land facefirst onto the slab.")
break
else:
print("You have to choose Yes or No")
And you can convert the input to a single case so you don't have to repeat the tests for yes and Yes.
you can do it by this way
print("Lying on the ground next to you is a stone slab.")
pick = input("Do you pick up the slab? Yes/No ")
print(" ")
if pick=="yes":
print("You pick up the slab and begin reading.")
elif pick=="no":
print("Lying on the ground next to you is a stone slab.")
else:
print("Answer Must Be 'Yes' or 'No'")
You can use a try except with raise to loop until you get a yes or no.
while True:
try:
pick = input("Do you pick up the slab? Yes/No ").lower()
print(" ")
if pick != "yes" && pick != "no":
raise IncorrectInput()
else:
#something
break
except IncorrectInput():
print("please input yes or no")
Use the while loop to check whether the input meets the rules, otherwise ask user to re-enter.
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No \n> ")
pick = pick.lower().strip()
if pick == "yes" or pick == "y" :
print("You pick up the slab and begin reading.")
break
elif pick =="no" or pick == "n":
print("You walk forwards and fall facefirst onto the slab.")
break
else:
print("Please input Yes/No.")
If you want to prompt user until the input is valid, you can use a loop:
print("Lying on the ground next to you is a stone slab.")
while True:
pick = input("Do you pick up the slab? Yes/No ").lower() # This will make the user input not case-senitive
try:
if pick == "yes":
print("You pick up the slab and begin reading.")
elif pick == "no":
print("Lying on the ground next to you is a stone slab.")
else:
raise Exception("Invalid input! Answer Must Be 'Yes' or 'No'")
except Exception as e:
print(e)
else:
break

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

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