Resolve syntax error by pressing enter on keyboard without typing anything

Asked

Viewed 51 times

1

Good night, you guys. My first post, I’m inciante and it may seem like a silly question but it’s keeping me up at night. I appreciate the help. In the code below, when pressing enter without typing anything in imput is returned an error and I tried everything but I still could not solve and I ended up not being able to follow the studies. Is there any way to fix it or is it normal?

cont = ('Zero', 'Um', 'Dois', 'Treis', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez',
        'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Desesseis', 'Desessete', 'Dezoito', 'Dezenove', 'Vinte')

for c in range(0, 20):
    num = int(input('Digite um número entre 0 e 20: ')).
    if 0 <= num <= 20:
        print(f'Você digitou o número {cont[num]}')
        next = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]
        if next == 'N':
            break
    else:
        print('Valor inválido! Tente novamente.')
print('Fim do Programa')

1 answer

1


You can treat the exception with try/except:

while True:
  try:
    num = int(input('Digite um número entre 0 e 20: '))
    break
  except ValueError:
    print("Digite somente números!")

With this while the entered value is not a number, the system will again prompt the user to enter a value.

See online: https://repl.it/@Dadinel/BusyFrailActiveserverpages


It is also possible to check the value in num before converting with the function int, using for example the method isdigit:

num = ""

while not num.isdigit():
  num = input('Digite um número entre 0 e 20: ')

num = int(num)

The idea is the same, while the value is not a number, the user stays within the while, thus requesting a new value.

See online: https://repl.it/@Dadinel/LavenderTemptingFirm


Just one observation, the function input already returns a str, therefore it is not necessary to convert, then in that stretch:

next = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]

You can remove the function str, 'cause you’ll get that return:

next = input('Deseja continuar? [S/N] ').upper().strip()[0]

Documentations:

https://docs.python.org/3/tutorial/errors.html

https://docs.python.org/3/library/stdtypes.html

https://docs.python.org/3/library/functions.html#input

  • Daniel Mendes, thank you very much for your answers. I will implement and sleep today rsrs.

Browser other questions tagged

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