0

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?

  • If the option is `E`, you try to convert it to a `int` first. In that case your program crashes because it's the string `E` and not a number. – mousetail Jan 29 '21 at 11:51
  • 1
    Use a while True - loop, use try: except: to catch validation error of option = int(option) - check for "E" in the except block and break from it. – Patrick Artner Jan 29 '21 at 11:52
  • Why convert to int at all ... check against the strings without converting to int. – Patrick Artner Jan 29 '21 at 11:57

2 Answers2

1

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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

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

Mata2907
  • 61
  • 7