Leonardo Lima’s answer is correct, but only a deeper explanation of why.
Generally speaking, it’s pretty simple.
See below the difference of this code:
luz_acessa = False
def interruptor():
global luz_acessa
if luz_acessa:
print("True: Luz acessa")
luz_acessa = False
else:
print("False: Luz apagada")
luz_acessa = True
for that code:
luz_acessa = False
def interruptor():
global luz_acessa
if luz_acessa:
print("True: Luz acessa")
luz_acessa = False
if not luz_acessa:
print("False: Luz apagada")
luz_acessa = True
and for a third example not cited above:
luz_acessa = False
def interruptor():
global luz_acessa
if luz_acessa:
print("True: Luz acessa")
luz_acessa = False
elif not luz_acessa:
print("False: Luz apagada")
luz_acessa = True
The if
, is nothing less than a conditional operator at code level, is a branch
at the processor level, but focusing on the code level, it aims to verify the veracity of the information placed after it. if these are true it executes the code that follows it.
When using the else
a path is created for when the information placed in the first is false, i.e.:
Se a luz estiver acesa:
Apague
Senão:
Acenda
Fim Se
In the code you posted, how did not use the operator else
for when the information is false, and instead used another operator if
which would cause the code to check each one separately and execute them one by one, and not dependently, follows an example of how its code executed:
Se a luz estiver acesa:
Apague
Fim Se
Se a luz estiver apagada:
Acenda
Fim Se
This exemplifies, that whenever their function is executed, the two will then perform, causing the first if
always be overwritten
As for the example cited by me, the else
as already mentioned creates a path for when the information is false, the difference from this to the else if
, is that the else if
creates a path for when the first information is false, but your information is true, follows example of the execution:
Se a luz estiver acesa:
Apague
Senão, se a luz estiver apagada:
Acenda
Fim Se
Supposing that the luz
had a third value other than true
or false
, for example a indefinido
, when the light was of value indefinido
it would neither be lit nor erased, and to alter that would have to, or put another else if
to check when it is undefined, or to place a else
at the end of everything so that this is always executed when the previous ones are not.
Anyway, I hope I helped