user error prevention, python code

Asked

Viewed 49 times

0

inserir a descrição da imagem aquiwell, I have some exercises in python because I am studying, I learned to format strings and use the other tools, however, I could not find a solution not to let the user make a mistake while executing the code, for example, write a string where it should be an integer number. the first part of the exercise does not have a prevention of user error, when I ask the age of the person to register, in other parts the while loop can meet well and does not let the user pass to the next step if the information typed is incorrect. If anyone has a solution that can help me I’d appreciate it.

print(f'REGISTER A PERSON')
conts = 0
conta = 0
cont2 = 0

while True:
    print(f'---' * 10)
    age = int(input(f'Type a age: '))
    sex = ' '
    while sex not in 'MmFf':
        sex = str(input(f'Type a sex: [M/F] ')).strip().upper()[0]
        if age < 18:
            conta += 1
        if sex in 'M':
            conts += 1
        if sex in 'F':
            if age < 20:
                cont2 += 1
    q = ' '
    while q not in 'YyNn':
        q = str(input(f'Do you want to continue? [Y/N] ')).upper().split()[0]
    if q == 'N':
        break
print(f'The total number of people under 18 is {conta}')
print(f'The total number of man registered is {conts}')
print(f'The total number of womans under 20 years old is {cont2}')

1 answer

0


A possible solution to your problem, would be to create a function to treat this case.

It could be implementing with a stream much like what you use in your reading function gênero or asks if quer continuar.

def lerEntradaNumeroInteiro():
    while True:
        entrada = input('Digite uma idade: ')
        try:
            idade = int(entrada)
            return idade
        except ValueError:
            print('Não foi possível representar o valor "{}" para um número inteiro válido'.format(entrada))

There are still some problems in using this approach because it will be possible to include negative values so it is necessary to treat this case too.

Then your code just use this function:

#...
while True:
    print(f'---' * 10)
    age = lerEntradaNumeroInteiro()
    sex = ' '
    #resto do código

Browser other questions tagged

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