Search code examples
pythonpgzero

Why is an integer variable used in an if statement?


In the following code snippet next_dot is used in an if statement, why?

def on_mouse_down(pos): 
    if dots[next_dot].collidepoint(pos): 
        if next_dot: 
            lines.append((dots[next_dot - 1].pos, dots[next_dot].pos))

        next_dot = next_dot + 1

    else:
        lines = []
        next_dot = 0

I do not understand what "if next_dot:" does and how it contributes to this code.


Solution

  • In python, a variable is "falsy" or "truthy", which means when an "if" statement evaluates the variable as an expression, it will give either false or true. Falsy variables are for example empty strings, empty lists, zero, and none, while truthy are those with values, for example [1,2,3] or 'foo'.

    if 0:
        # this code will never run
    
    if []:
        # this code will never run
    
    if 1:
        # this code will always run
    

    Since you do not want to run that function if next_dot is 0, because then you would get a negative index, he put an if statement.