Without the if explanation

Asked

Viewed 153 times

0

As far as I know, else should be below the if, corresponding it, but in the code below, Else is not next to the if , because it is outside the repeating structure, to be more exact, the else is not even identado, so the same was always to be executed and this does not happen. And yet the code works perfectly!

 L=[7,9,10,12]
 p=int(input("Digite um número a pesquisar:"))
 for e in L:
     if e == p:
        print("Elemento encontrado!")
        break 
 else: 
     print("Elemento não encontrado.")
  • In Python the command for may have a clause else. See the documentation.

  • 1

    Reading the documentation helps a lot. This is from for .. else and not of if .. else.

  • vlw guys, helped a lot was already getting crazy kkk

2 answers

1

It is not true that the else you should only come with one if, He can come to the situation when a bond has not been iterated to the end of what is expected. He was created precisely for the situation shown in this example.

It works just like the one you’d use on if. If the break is then triggered the else will not be executed. Serves for the while also.

When this clause exists break changes the semantics and works like a goto else (the normal would be a goto end).

Is that weird? Yeah, the right thing there would be a clause called then and not else, since it executes when the loop goes to the end and comes out naturally, but the language chose to use the same keyword as the if and change the semantics.

So we can conclude that the indentation is correct, it uses the same indentation as the for. It’s not outside the repeating structure, it’s together, a second part of it. And it’s obviously using it optionally when it makes sense.

Documentation.

0


This Else is part of the for and not of an IF, this is normal in Python, is characteristic of the language, according to documentation:

The else in your case is fired when none break is executed if a break then executed else will be fired.

Remember that in While we also have this, example:

i = 1
j = 10 # Mude para 11 para que o else não dispare
busca = 11

while i <= j:
    if i == busca:
        print('Valor 11 encontrado')
        break

    i = i+1

else:
    print("Não foi encontrado o 11")
  • Thank you brother, it helped a lot!

  • "If a break then executed else nay will be fired, "right?

  • @Rafaeltavares right, as I said: The Else in your case is fired when no break is run, if a break is run then Else will be fired.

Browser other questions tagged

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