Python while not true loops - python

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

Related

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 can I have my input be typed out again via using while loops and if statements?

So i have this simple problem and I am not so sure what to do even after trying it for quite sometime.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")
break
my issue is that I am not so sure what to type such that my input user has to type either yes or no instead of typing something else. Additionally, when I tried to run the program, when I typed yes/no it jumped straight to the else statement instead of the if statement.. someone pls help :( (am just a noob programmer)
I would remove the break in the else statement so that your program keeps looping until the user inputs yes or no.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")

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

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

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

Is there anyway to use 'return' outside a function block to go back to my variable from 'else'?

I've been facing this problem for a bit now. I know that the 'return' command can't work outside a function, but is there an alternative to this or is there a need to define a new function?:
print("Are you", userage(), "years old?")
userinput = input()
if userinput == "yes":
print("Ok, lets get on with the program")
elif userinput =="no":
print("Oh, let's try that again then")
userage()
else:
print("please answer yes or no")
return userinput
Btw, sorry for all the mistakes I make. I'm still a beginner.
You need to use a while loop here:
while (True):
userinput = input("Are you xxx years old?\n")
if userinput == "yes":
print("Ok, lets get on with the program")
break
elif userinput == "no":
print("Oh, let's try that again then")
else:
print("please answer yes or no")
The loop will ever only break when someone types in yes.

Categories

Resources