How to make the user return the specified condition when the same type wrong?

Asked

Viewed 1,434 times

1

In Python, when the user type a non-existent option, how do I ask him to type again one of the desired options?

Make a program where the user can type several values and register them in a list.

If the number already exists inside, it will not be added.

At the end will be displayed all unique values typed in an order crescent.

Below is the program I’m creating:

numeros=[]

while True:
    numeros.append(int(input('Digite um número: ')))
    condicao=str(input('Deseja continuar? SIM ou NÃO? ')).upper()

    if condicao=='NÃO':
        numeros.sort()
        unicos=list(set(numeros))
        #O comando  list(set(lista))  faz com que os números repetidos digitados não se repitam.
        print(f'Os números digitados (excluindo os duplicados) foram {unicos}')
        break

    elif condicao!='SIM':
    # Como faço para fazer o usuário retornar a "condicao" SIM ou NÃO?
        print('Essa opção não existe. Tente de novo.')
  • 1

    The code is not good, but it seems to do what you want or not? If not, then please explain better what you want.

  • I need that when the user falls under the condition "YES" or "NO", and mistakenly type something that is not either of these two options, I want it to return to condition until you type "YES" or "NO".

  • If-Elif-Else, pronto https://www.tutorialspoint.com/python/python_if_else.htm

  • Yeah, and it looks like that’s what your code is doing, if you don’t say what’s wrong and what you want it to help.

  • When I put the program to run and the user type something other than "YES" or "NO" the program returns for the user to enter a number instead of returning again the conditions "YES" or "NO". What I wanted to know is a way to make the user, in case he type wrong, repeat the operation until typing right.

2 answers

1

From what I understand, you want to implement a program that monte a list of numbers inteiros without repetições and, in the end, display them in order crescente. Well, the code below does tudo that.

from time import sleep

cont = 0
numeros = list()
continuar = True
while continuar == True:
    cont += 1
    if cont == 1:
        pa = 'algum'
    else:
        pa = 'outro'

    resp = input(f'Desejas digitar {pa} número? [S/N] ').strip()
    while resp not in 'SsNn':
        print('\033[31mValor INVÁLIDO! Digite apenas "S" ou "N"!\033[m')
        resp = input(f'Desejas digitar {pa} número? [S/N] ').strip()

    if (resp == 'S') or (resp == 's'):
        while True:
            try:
                n = int(input(f'Digite o {cont}º número: '))
                break
            except:
                print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[m')

        while n in numeros:
            print('\033[31mValor REPETIDO! Digite outro valor!\033[m')
            n = int(input(f'Digite o {cont}º número: '))
        numeros.append(n)

        continuar = True

    else:
        numeros.sort()
        print(f'\033[32mA lista gerada foi: {numeros}\033[m')
        print(f'\033[31mEncerrando o Programa!')
        for c in range(35):
            sleep(0.1)
            print(f'{chr(46)}', end='')
        continuar = False
        break

See here the functioning of the algorithm.

Please note that this program has some value treatments.

  1. First, it checks whether or not the entered value is a inteiro;
  2. Second, it checks whether the value inteiro is or is not contained in lista.

Note that the program only allows the insertion of values if the value is, inteiro and ainda não exista in the list. Otherwise, prohibits its insertion.

0


There are some ways to solve this, one of them would be like this:

numeros = []
while True:
    numeros.append(int(input('Digite um número: ')))
    while True:
        condicao = str(input('Deseja continuar? SIM ou NÃO? ')).upper()
        if condicao == 'SIM' or condicao == 'NAO': break
        print('Essa opção não existe. Tente de novo.')
    if condicao == 'NAO': break
numeros.sort()
unicos = list(set(numeros))
#O comando  list(set(lista))  faz com que os números repetidos digitados não se repitam.
print(f'Os números digitados (excluindo os duplicados) foram {unicos}')

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

So you isolate the repetition of just this part, one loop is different from the other, they must repeat different stretches independently. I improved some organization, but I didn’t fix other possible problems.

  • Got it! Thank you very much.

Browser other questions tagged

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