0
def admin():

    def admin_try():
        print ("1) Ver lista de productos.",'\n')
        print ("2) Agregar un producto.",'\n')
        print ("3) Modificar un producto (Precio).",'\n')
        print ("4) Eliminar un producto.",'\n')
        print ("5) Pedidos agendados.",'\n')
        print ("6) Salir.",'\n')
        global opcion
        opcion = int(input("Indique una opción valida: "))

    while True:
        try:
            admin_try()
        except (ValueError):
            print ("La instrución debe ser numerica.")
        admin_try()

admin()  # I get an error

I get an error when executing this code and I want to cycle with try, and I get this error at the time of executing the code. What I want is that whenever the user puts that wrong, the function is always executed.

Traceback (most recent call last): File "g:/proyecto/try.py", line 15, in admin admin_try() File "g:/proyecto/try.py", line 11, in admin_try opcion = int(input("Indique una opción valida: ")) ValueError: invalid literal for int() with base 10: 'uno' During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "g:/proyecto/try.py", line 20, in <module> admin() File "g:/proyecto/try.py", line 18, in admin admin_try() File "g:/proyecto/try.py", line 11, in admin_try opcion = int(input("Indique una opción valida: ")) ValueError: invalid literal for int() with base 10: 'one'

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

1 Answers1

0

Don't use try-except:

  • The need to use try-except arises from converting the input to an int
    • If you try to convert a non-numeric input to int, a ValueError exception will occur
    • This code can be executed without converting to an int
  • Use the membership operator, in to determine if the input is in the list of accepted inputs. If the input is not in the list, admin() is called again.
  • Setting opcion as a global variable is not required.
    • If it's required outside of admin(), use return.
    • If opcion is required as an int outside of the admin() function, then use return int(opcion)
def admin():
    print ("1) Ver lista de productos.",'\n')
    print ("2) Agregar un producto.",'\n')
    print ("3) Modificar un producto (Precio).",'\n')
    print ("4) Eliminar un producto.",'\n')
    print ("5) Pedidos agendados.",'\n')
    print ("6) Salir.",'\n')
    opcion = input("Indique una opción valida: ")

    while True:
        if opcion in ['1', '2', '3', '4', '5', '6']:
            return opcion  # return the value if it's needed outside of admin()
            break  # stops the loop because a correct option has been selected
        else:
            print ("La instrución debe ser numerica.\n")
            admin()

admin()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158