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

Asked

Viewed 2,096 times

4

How to make the system return some message like "This value must be numerical" in the problem below? (menu one and two have already been defined, this is just 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()

2 answers

7


The class int raises an exception of the type ValueError when the value to be converted to integer is not numerical, therefore, to ensure that the value entered by the user is numerical, just treat the exception.

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

Since it’s 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))
        menu[esc_menu]()
    except ValueError:
        print("O valor deve ser um número inteiro")
    except KeyError:
        print("Opção inválida")

See working on Repl.it

Since 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. Note that in this case I created the dictionary menu and invoked the proper function by menu[esc_menu](). I also defined the string message with the text to be displayed in the menu because, as are multiple lines, use the string between triple quotes will facilitate reading and maintenance of the code.

3

If it is only integers, you can use the function isdigit() or isnumeric() but cannot convert the input to int. Behold:

isdigit(): Return true if all characters in the string are alphabetical and there is at least one character, false otherwise. (Free translation)

isnumeric(): Return true if there are only numeric characters in S, False otherwise. Numeric characters include digit characters and all characters that have the Unicode numeric value property. (Free translation)

print("MENU PRINCIPAL")
while True:
  esc_menu = input("\n1) Ir para o menu um. \n"
  "2) Ir para o menu dois.\n "
  "\nEscolha uma opção: ")
  if esc_menu.isdigit() == False:
    print("Este valor deve ser numérico")
    
  if esc_menu == "1":
    print("OPCAO 01")
  if esc_menu == "2":
    print("OPCAO 02")

Remembering that it will only work for integers.
There may be easier ways.
isdigit() see working on repl it.
isnumeric() see working on repl it.

Reference

These functions indicate whether a particular string is entirely composed of numbers, if the string contain at least one character that invalidates this condition, they will return False.

  • These functions indicate whether a particular string is entirely composed of numbers, if the string contain at least one character that invalidates this condition, they will return False.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.