The class int
raises an exception of type ValueError
when the value to be converted to integer is not numeric, so to ensure that the value entered by the user is numeric, just handle the exception.
try:
esc_menu = int(input("..."))
except ValueError:
print("O valor deve ser um número inteiro")
As this is 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 at Repl.it
Since Python does not have the switch/case
structure, you can use a dictionary to store all the functions and thus avoid a large number of if
in a row. See that in this case I created the dictionary menu
and invoked the proper function doing menu[esc_menu]()
. I have also set the string message
with the text to be displayed in the menu, because, since there are multiple lines, using the string in triple quotes will facilitate reading and maintaining the code .