FunctionsΒΆ

You define functions using def:

def sayHello():
    print("hello")

sayHello()   # calls the function, which prints the word "hello"

Functions can take parameters:

def adder(a, b):
    print(a + b)

Note

Unlike Python, SNAPpy does not support optional/default arguments. If a function takes two parameters, you must provide two parameters. Providing more or fewer parameters gives an undefined result. There are a few built-in SNAPpy functions that do allow for optional parameters, but user-defined functions must always be called with the number of parameters defined in the function signature.

Functions can return values:

def adder(a, b):
    return(a + b)

print(adder(1, 2))  # would print out "3"

Functions can do nothing:

def placeHolder(a, b):
    pass

Functions cannot be empty:

def placeHolder(a, b):
    # ERROR! - you have to at least put a "pass" statement here
    # It is not sufficient to just have comments

This is also true for any code block, as might be found in a while loop or a conditional branch. Each code block must contain at least a pass statement.

Functions can change:

def sayHello(arg1, arg2, arg3):
    print("hello")

def sayHello():
    print("hello, world")

sayHello()   # calls the second function, which prints the word "hello, world"

If you have two function definitions that define functions with the same name, even with different parameter signatures, only the second function will be available. You cannot overload function names in SNAPpy based on the number or type of parameters expected.