Syntax error in if Else

Asked

Viewed 654 times

-2

frase1 = str(input("Digite uma frase: ").strip())
frase2 = str(input("Digite uma frase: ").strip())

print("O tamanho da frase1 é " ,len(frase1))
print("O tamanho da frase2 é " ,len(frase2))
if frase1 == frase2:
    print("SÃO IGUAIS")
    else:  //INVALID SYNTAX
        print("SÃO DIFERENTES")

What could be wrong with the code?

2 answers

6


The indentation of else is wrong. It should be on the same level as the if:

frase1 = str(input("Digite uma frase: ").strip())
frase2 = str(input("Digite uma frase: ").strip())

print("O tamanho da frase1 é " ,len(frase1))
print("O tamanho da frase2 é " ,len(frase2))

if frase1 == frase2:
    print("SÃO IGUAIS")
else:
    print("SÃO DIFERENTES")

Remember that all parsing in Python happens based on indentation. If you put the else inside the block of if, the interpreter will consider that it is an independent logical block that will be executed if the condition in the if is true. Like the else is not a valid block (without the if), a syntax error is triggered. The same problem can happen with other blocks, such as the if:

if frase1 == frase2:
     print("São iguais")
     if frase1 != frase2:
         print("São diferentes")

In this case, a syntax error would not be generated, but if the second if should be outside the first, the result of the program would be different than expected - that is, even if the sentences were different, no output would be generated. That is to say, take great care with indentation always.

  • Sorry to "noobice" but Python should not automatically indent?

  • No. Language does not have this power and should not, because all the logic of the application is built on indentation. At most the text editor you use has some tool that assists in indentation, but is completely independent of the language.

  • Anderson, Voce is a myth. Thank you so much for your help

3

The problem is that Else is tabulated, the correct would be:

frase1 = str(input("Digite uma frase: ").strip())
frase2 = str(input("Digite uma frase: ").strip())

print("O tamanho da frase1 é " ,len(frase1))
print("O tamanho da frase2 é " ,len(frase2))
if frase1 == frase2:
    print("SÃO IGUAIS")
else:
    print("SÃO DIFERENTES")

Browser other questions tagged

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