Python Programming Primer

Functions


Defining and calling a function

Functions in Python are defined using the def keyword. This is followed by the name of the function, the parameters, and the body of the function. Parameters are placed inside parentheses and separated by commas — the parentheses is followed by a colon. The body of the function is indented.

The following outlines how to define a function and how to call it. The function prints out the sum of the two arguments passed to it.

Run the program to see the output

Returning a value from a function

Like in many other programming languages, values are returned from a function using the return keyword. The following outlines how to define a function that returns the sum of the two arguments passed to it and uses the returned value as a part of a print statement.

Run the program to see the output

If a function does not return a value, it returns None.

Run the program to see the output

Loading Exercise...

Pass by assignment

When values are passed to a function in Python, they are passed by assignment. In effect, the arguments given to a function turn to variables within the scope of the function. This allows e.g. modifying instance variables of objects passed to a function, as well as modifying data collections within a function.

The following outlines how to modify a list inside a function. The changes made to the list are reflected also on the list outside the function as they are the same list in memory.

Run the program to see the output

On the other hand, in the following example, the list is reassigned inside the function. Due to this, any subsequent changes to the newly reassigned list within the function do not affect the list outside the function.

Run the program to see the output

Loading Exercise...