This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
When user input is anything different from the specified letters "A", "a", "B", "b", "C", "c", "E", "e", it doesn't run the else statement but just closes. I would also like to have it repeat the program again if user input is not any of the specified letters, how can I achieve that? I believe it would be something I'd have to add in the else statement.
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Python is very indentation specific. This should do the trick:
user_input = input()
if user_input in ("A", "a", "B", "b", "C", "c", "E", "e"):
if user_input == "A" or user_input == "a":
print("You chose A")
elif user_input == "B" or user_input == "b":
print("You chose B")
elif user_input == "C" or user_input == "c":
print("You chose C")
elif user_input == "E" or user_input == "e":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Your else should be part of the outer if (so same indentation), for now it is part of the inner if
Also you can simplify the tests, by first using .upper() to deal only with uppercase letters, and test the inclusion with user_input in "ABCDE"
user_input = input().upper()
if user_input in "ABCDE":
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
else:
print("Something went wrong, try again")
Ask again version
user_input = input("Please choose: ").upper()
while user_input not in "ABCDE":
print("Something went wrong, try again: ")
user_input = input().upper()
if user_input == "A":
print("You chose A")
elif user_input == "B":
print("You chose B")
elif user_input == "C":
print("You chose C")
elif user_input == "E":
print("You chose to exit the program")
Related
This is my code and I made it say "Please enter the right letter next time." when the incorrect base is inputted to the code, it does that it like:
Please enter the right letter next time.
None
How can I remove the "None" from appearing when ran?
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return print("Please enter the right letter next time.")
#main program
base1 = match_base("X")
print(base1)
It's because you're trying to return a print statement which doesn't make any sense.
Please change to:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return "Please enter the right letter next time."
#main program
base1 = match_base("X")
print(base1)
If you don't want to recover, use an exception.
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
raise ValueError("Please enter the right letter next time.")
If you do want to recover, let the caller do the work:
def match_base(base):
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
return None
base1 = match_base("X")
if not base1:
print("Please enter the right letter next time.")
else:
print(base1)
Note that this would be easier with a dictionary:
maps = {'A':'T', 'T':'A','C':'G','G':'C'}
def match_base(base):
return maps.get(base, None)
The reason you are getting None is because your program is trying to assign the print statement to a variable. print("Please enter the right letter next time.") cannot be a stored in a variable.
So it should look like this instead:
if base == "A":
return "T"
elif base == "T":
return "A"
elif base == "C":
return "G"
elif base == "G":
return "C"
else:
print("Please enter the right letter next time.")
Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...
This is the code that does not seem to work:
choice = input()
if input() == "1":
circle()
elif input() == "2":
square()
elif input() == "3":
triangle()
while input() != ("1" or "2" or "3"):
print("You have not chosen a correct number. Please try again.")
choice = input()
if input() == "1":
circle()
elif input() == "2":
square()
elif input() == "3":
triangle()
Basically the part that checks the correct number has been input does not seem to work and I don't know why, its only a logic error and i think its something to do with this part:
while input() != ("1" or "2" or "3"):
print("You have not chosen a correct number. Please try again.")
while input() != ("1" or "2" or "3"): is not correct.
("1" or "2" or "3") is a logical statement and resolves to the first non-empty or non-zero item:
>>> "1" or "2" or "3"
'1'
So the statement resolves to:
while input() != '1':
To correct it, use not in and a tuple:
while input() not in ("1", "2", "3"):
Alternatively, use the following pattern when asking for input and have a dispatch table of functions to eliminate the multiple if statements:
def circle():
print('circle')
def square():
print('square')
def triangle():
print('triangle')
funcs = {'1':circle,
'2':square,
'3':triangle}
while True:
choice = input()
if choice in ('1','2','3'):
break
print("You have not chosen a correct number. Please try again.")
funcs[choice]()
It looks like you're storing the input as choice but then calling input() again instead of using the value you already read.
Additionally, you can simplify this code significantly.
You should instead do the following:
choice = input()
while choice not in ("1", "2" ,"3"):
print("You have not chosen a correct number. Please try again.")
choice = input()
if choice == "1":
circle()
elif choice == "2":
square()
elif choice == "3":
triangle()
I'm stuck on this code I'm trying to complete. I want it to print "there's no more recipes left", but it prints "lets choose a different meal" twice.
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
for k,v in bank.items():
if my_choice in v:
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
elif choice == "n":
print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
else:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if len(my_choice) in food_bank.items() > len(v):
print("Sorry we have no more recipes")
First, the if choice == "y" and elif choice == "n" statement should inside if my_choice in v:
Second, when elif choice == "n" you need to know if that is the last recipe (i.e. 'recipe4').
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
for k,v in bank.items():
if my_choice in v:
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
elif choice == "n":
if "recipe4" != "recipe4":
print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
else:
print("Sorry we have no more recipes")
else:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"Your meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
If you enter ānā repeatedly, then once the loop gets to 'recipe4', which does not contain 'my_choice'/'["a","b","c"], then a new value is not set for 'choice'. So it sees ānā from last time, and prints the different meal text the second time.
Here's what I suggest for your code.
my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
"recipe2":[["a","b","c"], "g", "h", "i"],
"recipe3":[["a","b","c"], "j", "k", "l"],
"recipe4":["x", "y", "z"]}
# Create a list from your dictionary
bankList = list(bank.items())
# And then sort it according to whether 'my_choice' is in a given recipe
# This way, the later loop will go through the matching recipes first
bankList.sort(key=lambda recipe: my_choice in recipe[1], reverse=True)
choice = None
for k, v in bank.items():
if choice == "n":
print("Let's find you a different meal")
print(f"The meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
# If the user did not enter 'y' or 'n', keep asking until they do
while choice not in ["y", "n"]:
print("Please select y or n to keep your meal or select a different recipe.")
print(f"The meal we have chosen for you is {k,v}")
print("Do you like your meal? y/n")
choice = input()
if choice == "y":
print("Enjoy your meal!")
break
else:
# This code will only run if the loop completes without breaking
# In other words, if all recipes are considered and the user never says 'y' to any of them
print("Sorry, we have no more recipes")
New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])