0

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.

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41

2 Answers2

1

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.

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41
0

Welcome to Stack Overflow! For numbers, 0 will always evaluate to False. Everything else will evaluate to true. Also, because it is a number it can be incremented and the code inside the if block can be executed a precise number of times.

Joshua Hall
  • 332
  • 4
  • 15