Continue loop if input is’S'

Asked

Viewed 557 times

7

I tried to make a loop, that while the input is’S' it comes back and prompts again (it’s just for me to learn), if the input is 'N' it comes out of the loop, but is in loop infinite.

continuar = input("Deseja continuar? ")

while continuar == 's':
    print("Você está continuando")
else:
    print("Você saiu")

I tried to use the break but he interrupts the loop and for the show. I tried to use too: continuar += continuar, but I think it only works with numbers by the tests I’ve done.

3 answers

8


You probably want me to ask inside the loop as well, and you’re only accepting entering with lowercase, if you want uppercase (as per comment) you have to do:

continuar = input("Deseja continuar? ")
while continuar == 'S':
    print("Você está continuando")
    continuar = input("Deseja continuar? ")
else:
    print("Você saiu")

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

Without asking internally the variable will never change value in the loop so there is no way out, asking internally a time is typed a value that should come out and there closes.

In general not so much as it should do, something like this looks more like something real because it has no code repetition, including the idea is to accept any box:

while True:
    continuar = input("Deseja continuar? ")
    if continuar != 'S' and continuar != 's':
        break
print("Encerrou")

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

  • Oops, great, is there a specific command I can do to accept minute letters only ?

  • 1

    Capitalize the `S, because it currently only accepts lowercase.

  • Now I’m wearing tight pants, my friend from below replied correctly, can I mark his as the right answer to help him with his reputation as well? I don’t know how to proceed :(

  • 1

    @Codador To make it more difficult, I don’t know, but you can use the upper() command to transform the typed value into more. Or, you can use the Lower() command to turn the entered value into minuscule.

  • 2

    @Codador You should mark which one you think is best, you have the right to choose what you want, but we have a rule that you should not vote for the person, neither for one reason or another, what should be determined is the content. Which helped you the most? This is what should define, not the person’s current reputation, whether low or high.

  • 1

    @Codador, if the two answers helped you you can vote both as useful,What should I do if someone answers my question? , but can accept only one answer, What does it mean when an answer is "accepted"?.

  • 1

    Remembering that you can also use if continuar not in ('s', 'S')... in this case it makes no difference, but AP knowing this syntax makes it easier for cases with more test criteria.

  • A ta, beauty, personal thank you very much.

Show 3 more comments

4

The infinite loop is happening because you do not change or request a new value for the variable continuar, with this once the value is 's' it will never be altered and the loop becomes infinite.

You can fix this simply by placing the input inside the loop, thus requesting a new data entry, giving the user to exit the loop.

Take a look at this example:

continuar = input("Deseja continuar? ")

while continuar == 's':
    print("Você está continuando")
    continuar = input("Deseja continuar? ")
else:
    print("Você saiu")

Here the web executable example: https://repl.it/repls/NoteworthySupportiveConsulting

  • Oops, great, is there a specific command I can do to accept minute letters only ?

2

What you want can be solved using the following algritmo:

while True:
    print('Você está continuando!')

    # Capturando e avaliando a resposta.
    resp = input('Desejas continuar? [S/N]').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mDigite apenas "S" ou "N"!\033[m')
        resp = input('Desejas continuar? [S/N]').upper()
    if resp == 'N':
        break

Now, to show the logic of this working algorithm it is good to use a real case.

Well, suppose we have the following real case: Insert valores inteiros in a list until the moment you want to stop. At the moment you want to stop, type the letter N for the list mounted so far to be displayed, and wax the execution of the script.

In this case we can use the following script:

cont = 0
numeros = list()
while True:
    cont += 1

    # Verifica a palavra mais apropriada para solicitação dos valores.
    if cont == 1:
        msg = 'algum'
    else:
        msg = 'outro'

    # Solicita uma resposta "S" ou "N" para continuar ou encerrar a execução do laço.
    resp = input(f'Desejas inserir {msg} número? [S/N]? ').upper()
    while (len(resp) != 1) or (resp not in 'SN'):
        print('\033[31mDigite apenas "S" ou "N"!\033[m')
        resp = input(f'Desejas inserir {msg} número? [S/N]? ').upper()

    # Caso a resposta seja "S" iremos adicionar um valor à lista.
    if resp == 'S':
        while True:
            try:
                valor = int(input(f'Digite o {cont}º valor: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        numeros.append(valor)

    # Caso a resposta seja "N" o script exibe a lista e encerra sua execução.
    else:
        print(f'\033[32mA lista gerada foi:\n{numeros}\033[m')
        break

See here how the script works.

Note that when we run this script we receive the following message: Desejas inserir algum número? [S/N]?. At this point - if we really want to enter some number - we must press "S". Then we received the second message: Digite o 1º valor: . At this point we must enter the value and press enter. From then on, the script will check whether the entered value is inteiro. If yes, this value will be added to the list numeros. Otherwise, an exception will be raised until the user enters a value inteiro.

Later the script will be re-entered by displaying the following message: Desejas inserir outro número? [S/N]?. If we type right now "S", the value request process and, consequently, its insertion in the list numeros will be redone. If we type "N", the script will show the list containing all the values typed so far and will close the execution of the script.

Browser other questions tagged

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