TØ 3. Extra

This note contains additional exercises regarding functions and variables.

1 Functions

Functions in Python are like recipes in a cookbook. Writing them down does not “run” them, just like how writing down a recipe for a delicious brownie does not cause a delicous brownie to appear.

To “run” a function we need to call it, for example

1def my_func(x):
    result = 2 * x
    return result

2output = my_func(2)
1
Function definition, does not run the function.
2
Function call, runs the functions for the input x=2.

Additionally, if we want the function to influence our program we need to assign its output to a variable 1. Above we assigned the output of the function to the variable output, so we now have access to that variable

print("The output was: ", output)
The output was:  4

Then there is the concept of scope, the function we defined above defines a variable result, lets see what happens if we try to access it

print(result)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 print(result)

NameError: name 'result' is not defined

Python throws an error, telling us that result is not defined. This is because the result-variable is only available in the scope of the function. That means result only exists inside the function.

1.1 Exercise: Functions, calling, assignment and scopes

The code block above defines two functions.

Below there are three code blocks that use these functions and an accompanying question. Use the interactive codeblock below to answer these questions.

You are not expected to give technically precise answers, just describe it in your own words. For each question you can play around with the interactive block or the definition of the functions above to help you answer.

1.1.1 Without assignment

What happens when the functions are called but the output not assigned?

1.1.2 With assignment

What happens when the functions are called and the output is assigned?

1.1.3 Without calling

What happens when you assign the function itself to a variable without calling it?

Footnotes

  1. This is a little bit imprecise. Functions can be written to change variables, or more generally the program state in-place or have other side-effects. However, the functions we will consider in this course are not of this type.↩︎