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")
Related
I'm trying to create a sort of CLI menu in Python (very new to this) and having an issue with the quit option mostly, it won't actually quit and jumps to the "Oooops that isn't right" option instead, or repeats the last step. It does seem to work if you put it as the first choice though
I know I must be doing something daft. I've tried just putting the variable at the end of the function, as well as the menu function itself but that didn't seem to work.
Snippet below if anyone can point me in the right direction.
def my_menu():
choice = input("Please choose an choice: ")
choice = choice.lower()
while (choice != "quit"):
if choice == "b":
a_thing()
my_menu()
if choice == "quit":
break
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
Try to input the choice another time at the end of the loop, remove the call to the my_menu() function and remove the if choice=="quit" block (because the loop will automatically quit when the choice is set to "quit")
def my_menu():
choice = input("Please choose an choice: ").lower()
while (choice != "quit"):
if choice == "b":
a_thing()
else:
print("Oooops that isn't right")
choice = input("Please choose an choice: ").lower()
def a_thing():
print("a thing")
my_menu()
Or you can remove the loop and just verify using if statements and in the case of "quit" you just put return to break the loop
def my_menu():
choice = input("Please choose an choice: ").lower()
if choice == "b":
a_thing()
elif choice == "quit":
return
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
I ran your code, and on its first iteration it runs as expected. After that, the recursive call to my_menu() starts to cause problems.
Walking through it, first you enter some random string, "hi", and it will enter the while loop and use the else case. This will call my_menu(), which then calls another while loop. When you enter that new while loop, any exiting that you do (e.g. break) won't exit the first loop, only the loop that your currently in, so you're in an infinite loop because you can never "go back" and change the value of choice in the first loop.
A way you could achieve this behavior with the least amount of changes to your code would be like this:
def my_menu():
choice = ""
while (choice != "quit"):
choice = input("Please choose an choice: ")
choice = choice.lower()
if choice == "b":
a_thing()
if choice == "quit":
break
else:
print("Oooops that isn't right")
def a_thing():
print("a thing")
my_menu()
(I removed your recursive calls to my_menu(), moved the input lines to within the loop, and initialized choice before the loop)
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")
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.
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
I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.