It first runs the code after it checks
This is not true, I believe that for any language.
if 1 > 2:
print('Isso nunca vai ser executado.')
In the above example, the print
will not be executed.
If the code within your if
is running when it should not, it is because the condition evaluated by it resulted in True
. I suggest you use a debugger or print
in your variables to understand what is going on and where the wrong assumption is.
Regarding what you heard, you probably misunderstood the following:
What may happen is that you may check a condition so that it has side effects. For example:
def verificar_xyz():
print('Isso sempre será executado.')
return False
if verificar_xyz():
print('Isso nunca será executado.')
In this case, the block within if
will not be executed because verificar_xyz
returns False
, but print
inside the function is executed, because the function executes normally up to return
. / p>
In if
or other condition check, if one of the conditions in and
is negative, the evaluation stops immediately. This means that, for example, the following passages behave differently:
if verificar_xyz() and 1 > 2:
print('Isso nunca será executado.')
Here the block within if
will not execute, but the verificar_xyz
function has been executed and the text "This will always be executed" from within the function is shown on the screen. 1 > 2
is not evaluated because the first evaluated condition has already returned False
.
if 1 > 2 and verificar_xyz():
print('Isso nunca será executado.')
Here the "This will always be executed" function of the verificar_xyz
function will not run because since 1 > 2
results in False
, Python (or other language) and
can not be true and immediately skips the block, without evaluating verificar_xyz()
.
Therefore, it is recommended that the functions used in condition evaluations have no side effects. This can lead to subtle bugs.