Who runs the condition or the code block first in Python?

-1

People have a problem and I believe it's because of the execution order I can not run such a block of code if it does not pass first for a condition if it is not going to give error, and once hear that in C it first run the code then check, is this true? And how is it in python?

 menor = 9999999999999999999999999999
    valor_k = 0
    for k in range(self.numero_vertices): 
        if (grafo.number_of_edges(v,k) == 1): # se for diferente de 1 não deveria fazer nada so aumentar o valor de k no for
            if (grafo[v][k]['tamanho'] < menor and self.verifica_fonte(grafo, k, v) == True):
                menor = self.grafo[v][k]['tamanho']
                valor_k = k
    return valor_k
    
asked by anonymous 19.05.2018 / 20:13

1 answer

0
  

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.

    
19.05.2018 / 20:57