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.
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
.– NoobSaibot