In my program I have a menu that looks like this:
MenuChoice = ''
while MenuChoice != 'x':
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
try:
MenuChoice = str(input("Please enter your choice here ----------------->>>>>"))
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
I just want to know a way in which I can insure that only the numbers 1 to 5 are accepted and that if anything else is entered then the program asks the question again.
Please dont roast me.
Thanks
You're right to use a while loop, but think of what condition you want. You want only the numbers 1-5 right? So it would make sense to do:
MenuChoice = 0
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while not (1 <= MenuChoice <= 4):
MenuChoice = input("Please enter your choice here ----------------->>>>>")
if MenuChoice == 'x' : break
try:
MenuChoice = int(MenuChoice)
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
MenuChoice = 0 # We need this in case MenuChoice is a string, so we need to default it back to 0 for the conditional to work
We make our input an integer so that we can see if it's between 1-5. Also, you should put your beginning print statements outside of the loop so it doesn't continually spam the reader (unless this is what you want).
I think he needs a While true loop . Did using python 2.X
import time
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while True:
try:
print ("Only Use number 1 to 4 or x to Quit... Thanks please try again")
MenuChoice = raw_input("Please enter your choice here ----------------->>>>> ")
try:
MenuChoice = int(MenuChoice)
except:
MenuChoice1 = str(MenuChoice)
if MenuChoice1 == 'x' or 1 <= MenuChoice <= 4:
print "You selected %r Option.. Thank you & good bye"%(MenuChoice)
time.sleep(2)
break
except:
pass
Related
Trying to validate user input in my program.
playerChoice = int(input("Enter your choice: "))
while playerChoice != 1 and playerChoice != 2 and playerChoice != 3 and playerChoice !=4:
print("Please make a valid selection from the menu.")
playerChoice = int(input("Enter your choice: "))
This works great as long as the input is an integer (the problem statement specifically states the input is an integer). However, if I enter 1.5 or xyz, I get an unhandled ValueError exception.
So I changed it:
try:
playerChoice = int(input("Enter your choice: "))
while playerChoice not in(1, 2, 3, 4):
print("Please make a valid selection from the menu.")
playerChoice = int(input("Enter your choice: "))
except ValueError:
print("Please enter a number.")
playerChoice = int(input("Enter your choice: "))
which also works great...once. I know the solution here is simple but I can't figure out how to get the code into a loop that will handle other data types. What am I missing?
Sorry for asking such a dumb question.
It is because you put the try ... except clause outside of the loop, while you want it to be inside of it.
playerChoice = None
while not playerChoice:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice not in(1, 2, 3, 4) :
print("Please make a valid selection from the menu.")
playerChoice = None
except ValueError:
print("Please enter a number.")
Put the try/except inside your loop:
while True:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice not in (1, 2, 3, 4):
print("Please make a valid selection from the menu.")
else:
break
except ValueError:
print("Please enter a number.")
Put a while loop around the whole thing.
while True:
try:
playerChoice = int(input("Enter your choice: "))
if playerChoice in(1, 2, 3, 4):
break
print("Please make a valid selection from the menu.")
except ValueError:
print("Please enter a number.")
Notice that by putting the input() call inside the main loop, you only have to write it once, rather than repeating it after all the validation checks.
# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)
I am trying to get the user to input either 1, 2, or 3. If none of the numbers are entered an error message will be displayed and the program will ask for input again.
How do i identify if what the user typed is either 1,2, or 3?
This is what i currently have.
while True:
try:
userInput = input("Enter a number: ")
if userInput not in range(1,4):
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
elif userInput.isdigit('1'):
print('1')
elif userInput.isdigit('2'):
print('2')
else:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
If you want your input to be in range(1, 4), it needs to be an int, not a str (which is what's returned by input():
while True:
try:
userInput = int(input("Enter a number: "))
assert userInput in range(1, 4)
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
if userInput == 1:
print('1')
if userInput == 2:
print('2')
if userInput == 3:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
break
You have to check values of the same type. Your code compares string and int. You also need to work on the syntax of basic statements: if <condition>: except: isn't legal. Keep it simple:
userInput = None
while userInput not in ['1', '2', '3']:
userInput = input("Enter a number: ")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I was trying to use an "Input" function to prompt a user to select an option.
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
option = input("Please select an option: ")
while option != "E" and int(option) < 1 or int(option) > 2:
option = input("Please select a valid option: ")
if int(option) == 1:
dataset = pd.read_csv("portfolioStock.csv")
with open("portfolioStock.csv", newline='') as file:
for row in csv.reader(file):
stock.append(row)
elif int(option) == 2:
filename = input("Please enter filename with the extension:")
dataset = pd.read_csv(filename)
with open(filename, newline='') as file:
for row in csv.reader(file):
stock.append(row)
elif option == "E":
print("Press enter to return to menu.")
However when I debug the code, input 1 and 2 works well but an input E generated an error message "ValueError: invalid literal for int() with base 10: 'E'"
I have tried to print out the type of my input and it gives me "str" as expected. So I have no idea where my code goes wrong. Can anyone help me with this issue?
The line
while option != "E" and int(option) < 1 or int(option) > 2:
will always convert option to int to verify the second half of the and condition.
You do not even need the integers - simply compare for string values.
Not using integers at all - they are not needed for your usecase:
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
while True:
option = input("Please select an option: ") # add .upper()?
if option not in ('1', '2', 'E'):
print("Invalid choice. 1, 2 or 'E' allowed.")
continue
if option == "1":
print(" Choice --> ", option)
elif option == "2":
print(" Choice --> ", option)
else: # "E"
print(" Choice --> ", option)
print("Quitting\n")
break
Or do it like it is done in Change your logic according to Asking the user for input until they give a valid response:
Using try: .. except: ... and integer conversion:
print("\n1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
while True:
try:
option = input("Please select an option: ")
option = int(option)
if option not in (1, 2):
raise ValueError() # outside bounds
print(" Choice --> ", option)
except ValueError:
if option == "E":
print("Quitting\n")
break
else:
print("Invalid choice. 1, 2 or 'E' allowed.")
(Indentical) Output for both codes:
1. Default Data Sheet
2. Upload Data Sheet
E. Exit
Please select an option: 4
Invalid choice. 1, 2 or 'E' allowed.
Please select an option: e
Invalid choice. 1, 2 or 'E' allowed.
Please select an option: 1
Choice --> 1
Please select an option: 2
Choice --> 2
Please select an option: E
Choice --> E
Quitting
"E" is a string, not a number. When you choose "E", the code stops at the while condition. Try to convert the variable "option" as a string type. You must change also the while condition
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
option = input("Please select an option: ")
while (option != "E" and str(option) != "1" and str(option) != "2"):
option = input("Please select a valid option: ")
if str(option) == "1":
print("you press 1")
elif str(option) == "2":
print("you press 2")
elif str(option) == "E":
print("Press enter to return to menu.")
Hope that helps.
I'm writing this program that is basically a limited calculator. I'm trying to make it so that if the user enters let's say "Power" instead of the number 1 for the desired mode, it prints out "Invalid selection". The same goes if they attempt to write "Quadratics" instead of 2 and so on for the rest.
#CALCULATOR
print("MY CALCULATOR")
print("1. Powers")
print("2. Quadratics")
print("3. Percents")
print("4. Basic Ops")
choice = int(input("Please enter your desired mode: "))
if choice == 1:
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
power = base**exponent
if choice == 2:
print("Please enter the values for A/B/C: ")
a = int(input("A: "))
b = int(input("B: "))
c = int(input("C: "))
I tried doing:
if choice not == 1:
print("Invalid Selection")
and
if choice not 1:
print("Invalid Selection")
but they don't seem to work. If you could please tell me what I am doing wrong. Thank you.
not is not a function. It is an operator.
The correct usage is to put it before an expression:
if not (choice == 1):
However in this case, it's much better to use != (not equal) instead:
if choice != 1: