Syntax error no if else

-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?

    
asked by anonymous 06.10.2017 / 19:25

2 answers

6

The indentation of else is wrong. It should be on the same level as 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 of the syntax analysis in Python happens based on indentation. If you put else inside the if block, the interpreter will consider that it is an independent logical block that will be executed if the condition in if is true. Because else is not a valid block (without if ), a syntax error is triggered. The same problem can happen with other blocks, such as if itself:

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 was to 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, be very careful with the indentation always .

    
06.10.2017 / 19:27
3

The problem is that the else is tabbed, the correct one 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")
    
06.10.2017 / 19:26