While loop in PYTHON

Asked

Viewed 355 times

3

Hello,
I’m making a program to save 'url' just to put into practice what I’ve been studying in Python. During the elaboration of the same I reached a lock and after days studying and reading and trying to get out of it, I could not solve. I read it on the forum to see if I could find anything that would help me, but I couldn’t find anything. I am new to programming and I apologize if my code does not conform to some formatting pattern.

The catch I got was that if I type an option other than 0, 1, 2 or 9, the program simply stops, not going to the Else, as I hoped it would be.

import sys  

print('--\tOpções\n'  
     '0\t-\tInserir \'url\' a lista.\n'  
     '1\t-\tVisualizar lista de \'url\'.\n'  
     '2\t-\tApagar \'url\' da lista (de acordo com a posição numérica).\n'  
     '9\t-\tSair do programa')  

escolha = 1000  
opcoes = int(input('Digite a opção desejada: '))

while opcoes == 0 or 1 or 2 or 9:

    if opcoes == 0 and escolha != 0:
        url = str(input('Digite a \'url\' destinada a armazenamento: '))
        arquivo = open('url.txt','a')
        arquivo.write(url + '\n')
        arquivo.close()
        escolha = int(input('\nDeseja armazenar outra \'url\'? SIM[\'1\'] / NÃO[\'0\']: '))
    if escolha == 0:
        escolha = int(input('\t0\t-\tFechar o programa\n'
                '\t1\t-\tMENU anterior: \n'
                'Deseja: '))
        if escolha == 0:
            print('\nAté logo!')
            sys.exit()
        elif escolha == 1:
            print('\n--\tOpções\n'
                '0\t-\tInserir \'url\' a lista.\n'
                '1\t-\tVisualizar lista de \'url\'.\n'
                '2\t-\tApagar \'url\' da lista (de acordo com a posição numérica).\n'
                '9\t-\tSair do programa')
            opcoes = int(input('Digite a opção desejada: '))

    if opcoes == 1 and escolha != 0:
        arquivo = open('url.txt', 'r')
        for linha in arquivo:
            print(linha.rstrip())
        arquivo.close()
        escolha = int(input('\nDeseja continuar usando o programa? SIM[\'1\'] / NÃO[\'0\']: '))
        if escolha == 0:
            print('Até logo')
            sys.exit()
        elif escolha == 1:
            print('\n--\tOpções\n'
                    '0\t-\tInserir \'url\' a lista.\n'
                    '1\t-\tVisualizar lista de \'url\'.\n'
                    '2\t-\tApagar \'url\' da lista (de acordo com a posição numérica).\n'
                    '9\t-\tSair do programa')
            opcoes = int(input('Digite a opção desejada: '))

    if opcoes == 2:
        print('Em construção')
        escolha = int(input('\nDeseja continuar usando o programa? SIM [\'1\'] / NÃO[\'0\']: '))
        if escolha == 0:
            print('Até logo')
            sys.exit()
        elif escolha == 1:
            print('\n--\tOpções\n'
                  '0\t-\tInserir \'url\' a lista.\n'
                  '1\t-\tVisualizar lista de \'url\'.\n'
                  '2\t-\tApagar \'url\' da lista (de acordo com a posição numérica).\n'
                  '9\t-\tSair do programa')
            opcoes = int(input('Digite a opção desejada: '))

    if opcoes == 9:
        print('\nAté logo!')
        sys.exit()

else:
    print('Você escolheu uma opção inválida')

print('Testando se está saindo do laço')
input()

I’ve been reading here for a while, but no account logged in before, but it’s the first question I ask. I have read the patterns that must be obeyed for question formatting, but I apologize if I missed any.

edit1: I put a test when coming out of the loop while just to see if it was coming out and not, it’s not coming out of the loop. As well as Else. The program only for.

  • 1

    I put more information in my reply - I hope I have not left even more confused!

  • 1

    Did not let! It was very clear. Thank you for all your attention and care!

2 answers

4


Your loop while:

while opcoes == 0 or 1 or 2 or 9:

Could be written as:

while opcoes == 0 or True or True or True:

If opcoes is not 0, the expression will remain:

while False or True:

which in the truth table will result in only True - that is, its loop is infinite.

And there’s no problem at first in using an infinite loop - but it seems to me that you missed the indentation, and the last one is out of the loop:

#...
    if opcoes == 9:
        print('\nAté logo!')
        sys.exit()

# o else abaixo está fora da avaliação de 'opcoes'
else:
print('Você escolheu uma opção inválida')

But if you put it in the loop, your while infinity will fill your screen with "You chose an invalid option". So you need to, once again, ask for user input:

else:
print('Você escolheu uma opção inválida')
opcoes = int(input('Digite a opção desejada: '))

That said, I suggest you rewrite your code. Every time you notice that your code is repetitive, and that you’re copying and pasting ready-made parts like the menu, in your case, there’s something wrong.

A "logical" way to do this would be to create a while that only cares about the "quit" command - and it would be interesting also you try to remove all copies of menus you made, and ask for user input within that loop while - I’d start again like this:

opcoes = 0
while opcoes != 9:
  print('--\tOpções\n'  
    '0\t-\tInserir \'url\' a lista.\n'  
    '1\t-\tVisualizar lista de \'url\'.\n'  
    '2\t-\tApagar \'url\' da lista (de acordo com a posição numérica).\n'  
    '9\t-\tSair do programa')  

  opcoes = int(input('Digite a opção desejada: '))
  if opcoes == 0:
    print("Testando opção 0")
  if opcoes == 1:
    print("Testando opção 1")
  if opcoes == 2:
    print('Em construção')
  if opcoes == 9:
    print('\nAté logo!')

Edit

To better explain the while case:

while opcoes == 0 or 1 or 2 or 9:

opcoes == 0 is an expression that can be evaluated in True or False - while opcoes == 0 for True, the loop executes.

But his while has other "expressions" between each of the or.

1 is an expression, which in Python is evaluated in True.
2 is also an expression that in Python is evaluated in True.

That’s why the other answer solution works - it changes the "expression" 1 for opcoes == 1 - it gives the expression, the possibility of being evaluated in False, and the loop is no longer infinite.

Supposing opcoes is not equal to 0, opcoes == 0 would be false. And with 1 being evaluated to True, you end up with the following while:

while False or True:

And if you check the truth table for OR, will see that the result is True and so the loop spins endlessly.

2

Make it so buddy, I’m sure it’ll work, no loop while puts:

while opcoes == 0  or opcoes == 1 or opcoes == 2 or opcoes == 9:
  • Thank you! Solved my problem. I came up with another question with your answer, but by mistake my own. Before it was working if I didn’t bring the error to the program. I want to say the following: if I typed within the program, it 'activated'' the loop while. It was only if I went out of the forecast that what I described above would happen. Doing it the way you instructed me works, but why did it go half right and half wrong before? You know how to say?

  • 1

    Sorry man, I can’t answer you, if there was some error in the execution of the script I could know, but now you know how to solve, and you will do the same thing in the next code you will build!

  • Thank you so much anyway! I will be doing tests here to see if I can 'me' answer. Again, thanks for your attention!

Browser other questions tagged

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