Try no for - PYTHON

Asked

Viewed 57 times

-4

Guys, how do I use Try no for? When it falls in except and the person type a string, it gives another error and terminates the program, in while I can use normally. I tried using a for loop with while, but the program does not repeat the option that was typed in the string but goes to the next one.

for k in range(1, 6):
    try:
        teste1 = float(input(f'test {k}: '))
        teste.append(teste1)
    except ValueError:
        print('Erro, tente novamente')
        teste1 = float(input(f'test {k}: '))
        teste.append(teste1)


print(teste)
  • for each element of for, you need repeat endlessly the question until the user type correctly. Use a while within your for.

1 answer

1

An alternative is to initialize the teste1 variable as a string and check its type, in case the casting to float goes wrong it goes back to the starting line of while, until the person enters something valid

Taking advantage of your logic:

teste = []
for k in range(1, 6):
    teste1 = ''
    while type(teste1) != float:
        try:
            teste1 = float(input(f'test {k}: '))
            teste.append(teste1)
        except ValueError:
            print('Erro, tente novamente')

print(teste)

Browser other questions tagged

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