How to make the system display an error message when it is not number?



  • How to get the system to return some type message "This value must be numerical" in the problem below? (menu one and two have already been defined, this is only a cut)

    print("MENU PRINCIPAL")
    while True:
        esc_menu = int(input("\n1) Ir para o menu um. \n"
                             "2) Ir para o menu dois.\n "
                             "\nEscolha uma opção: "))
        if esc_menu == 1:
            menu_um()
        if esc_menu == 2:
            menu_dois()
    


  • The class int raises an exception of the type ValueError when the value to be converted to whole is not numeric, so to ensure that the value entered by the user is numeric, just treat the exception.

    try:
        esc_menu = int(input("..."))
    except ValueError:
        print("O valor deve ser um número inteiro")
    

    As it comes to a menu, you could do something like:

    def menu_um(): print("Menu 1")
    def menu_dois(): print("Menu 2")
    

    message = """

    1. Ir para o menu um.
    2. Ir para o menu dois.

    Escolha uma opção:
    """

    menu = {
    1: menu_um,
    2: menu_dois
    }

    print("Menu")

    while True:
    try:
    esc_menu = int(input(message))
    menuesc_menu
    except ValueError:
    print("O valor deve ser um número inteiro")
    except KeyError:
    print("Opção inválida")

    See working on https://repl.it/@acwoss/ImpracticalAmusingAmericanlobster

    How Python does not have the structure switch/case, you can use a dictionary to store all functions and thus avoid a large number of if followed. See that in this case I created the dictionary menu and invoked due function by doing menuesc_menu. I also define string message with the text to be displayed in the menu, because, as are multiple lines, use the string between triple quotes will facilitate the reading and maintenance of the code.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2