invalid.syntax appears when the program runs

0

I have tried to put palavra = '' and the same error continues to appear:

lista = []
i = 0
while (palavra != 'Sair') or (palavra != 'sair'):
    i += 1
    palavra = str(input('digite alguma palavra: ')
    lista.append(palavra)
print(lista)
    
asked by anonymous 28.09.2018 / 19:57

2 answers

0

The parentheses of the input to string conversion are missing from the following line:

palavra = str(input('digite alguma palavra: ')

Should be:

palavra = str(input('digite alguma palavra: '))
    
28.09.2018 / 20:28
0

As already mentioned, the parentheses of str are missing. But input already returns a string, so str is not necessary in this case.

Another thing is the while condition. The or is true if any of the conditions are true. And while the condition is true, while continues to execute.

So, (palavra != 'Sair') or (palavra != 'sair') means "if the word is not 'Exit' or if the word is not 'quit'". What happens if the word is "Exit"?

  • The first condition ( palavra != 'Sair' ) is false because the word equals "Exit"
  • The second condition ( palavra != 'sair' ) is true, because the word is not equal to "exit"

Because one of the conditions is true, the result of or is true, so it does not exit the loop. To correct, just change or by and , since and will only be true if both conditions are true (if one of them is false, it exits from while ):

while (palavra != 'Sair') and (palavra != 'sair'):

Or use lower() to convert the string to lowercase, so you only need to compare it to "exit."

Another thing is that you do not use the i variable for anything, so you can take it too.

But there is still a detail. Viewing the code below (with the modifications suggested so far):

lista = []
palavra = ''
while palavra.lower() != 'sair':
    palavra = input('digite alguma palavra: ')
    lista.append(palavra)

print(lista)

The above code includes the word "exit" in the list, because within while the word is read, added to the list and only checked if it equals "exit."

If you do not want the word "exit" to be in the list, you should check this before inserting it into the list. In this case you can use and use break , which interrupts while :

lista = []
while True:
    palavra = input('digite alguma palavra: ')
    # se a palavra for "sair", sai do loop (e não coloca a palavra na lista)
    if palavra.lower() == 'sair':
        break
    lista.append(palavra)

print(lista)

Remember that using lower() works for this case because I'm comparing it to a string that only has ASCII characters ( sair ). But for a comparison that involves other characters (used in other languages, such as ß or fi) I suggest viewing this SOen response .

    
29.09.2018 / 03:00