Finnish university students are encouraged to use the CSC Notebooks platform.
Others can follow the lesson and fill in their student notebooks using Binder.
In this lesson we introduce functions as a way of making blocks of code for a specific task that are easy to use and re-use in your programs.
This lesson is partly based on the Software Carpentry group's lessons on Programming with Python.
A {term}function (funktio)
is a block of organized, reusable code that can make your programs more effective, easier to read, and simple to manage.
You can think functions as little self-contained programs that can perform a specific task that you can use repeatedly in your code.
One of the basic principles in good programming is "do not repeat yourself".
In other words, you should avoid having duplicate lines of code in your scripts.
Functions are a good way to avoid such situations and they can save you a lot of time and effort as you don't need to tell the computer repeatedly what to do every time it does a common task, such as converting temperatures from Fahrenheit to Celsius.
During the course we have already used some functions such as the print()
function which is a built-in function in Python.
Let's consider the task from the first lesson when we converted temperatures from Celsius to Fahrenheit. Such an operation is a fairly common task when dealing with temperature datasets. Thus we might need to repeat such calculations quite often when analysing or comparing weather or climate data between the US and Europe, for example.
Let's define our first function called celsius_to_fahr
.
The function definition opens with the keyword def
followed by the name of the function and a list of parameter names in parentheses. The body of the function, the statements that are executed when it runs, is indented below the definition line just like for for loops or conditional statements.
When we call the function, the values we pass to it are assigned to the corresponding parameter variables so that we can use them inside the function (e.g., the variable temp
in this function example).
Inside the function, we use a return
statement to define the value that should be given back when the function is used, or called.
Defining a function does nothing other than make it available for use in our notebooks. In order to use the function we need to call it.
Now let's try using our function.
Calling our self-defined function is no different from calling any other function such as print()
.
You need to call it with its name and provide your value(s) as the required parameter(s) inside the parentheses.
Here, we can define a variable freezing_point
that is the temperature in degrees Fahrenheit we get when using our function with the temperature 0°C (the temperature at which water freezes). We can then print that value to confirm. We should get a temperature of 32°F.
We can do the same thing with the boiling point of water in degrees Celsius (100°C). Just like with other functions, we can use our new function directly within something like the print()
function to print out the boiling point of water in degrees Fahrenheit.
Now that we know how to create a function to convert Celsius to Fahrenheit, let’s create another function called kelvins_to_celsius
. We can define this just like we did with our celsius_to_fahr()
function, noting that the Celsius temperature is just the temperature in Kelvins minus 273.15. Just to avoid confusion this time, let's call the temperature variable used in the function temp_kelvins
.
Note:It would be perfectly fine to use the variable name temp
inside our new function as well. As you will see below, variables defined in functions exist only within the function itself and will not conflict with other variables defined in other functions.
Let's use it in the same way as the earlier one by defining a new variable absolute_zero
that is the Celsius temperature of 0 Kelvins. Note that we can also use the parameter name temp_kelvins
when calling the function to explicitly state which variable value is being used. Again, let's print the result to confirm everything works.
Isaac Newton developed a scale for measuring temperatures that was a precursor to the modern-day Celsius scale. In his system, water would freeze at 0 °N and boil at 33 °N (°N here indicates degrees Newton, not degrees north :D). Although it is difficult to directly convert between the two scales, if we assume that the increments of temperature change are equal between 0 °N and 33 °N we can come up with a temperature conversion equation between degrees Celsius and degrees Newton:
$$ \begin{equation} \Large T_{\mathrm{Newton}} = T_{\mathrm{Celsius}} * 0.33 \end{equation} $$You task here is to:
celsius_to_newton
that# Enter your code below
What about converting Kelvins to Fahrenheit?
We could write out a new formula for it, but we don’t need to.
Instead, we can do the conversion using the two functions we have already created and calling those from the function we are now creating. Let's create a new function kelvins_to_fahr
that takes the temperature in Kelvins as the parameter value temp_kelvins
and uses our kelvins_to_celsius
and celsius_to_fahr
functions within the new function to convert temperatures from Kelvins to degrees Fahrenheit.
Now let's use the function to calculate the temperature of absolute zero in degrees Fahrenheit. We can then print that value to the screen again.
A common point of confusion for new programmers is understanding how variable names in functions relate to those defined elsewhere in your notebooks. When defining a function, the variable names given in the function definition exist and will only be used when the function is called. That might seem confusing, but as it turns out, this is an excellent feature in Python that can save you from much suffering. Let's try to understand this by way of an example.
Let us define modified version of our kelvins_to_celsius
function where the parameter value is still called temp_kelvins
, but we now store the converted temperature as temp_celsius first and return that value.
So, we have defined our function to accept temp_kelvins
as its only parameter, calculate temp_celsius
, and return that value.
As you will see below, the variables defined in the function exist only in its namespace.
Let's confirm that.
Here, in the global namespace we get a NameError
when trying to access the variables temp_kelvins
or temp_celsius
because they have only been defined within the kelvins_to_celsius()
function.
Perhaps, however, you are thinking that we have not yet called the function, so that is why we get a NameError
. Maybe if we use the function, then these variable values will be defined.
Let's try that.
As you can see temp_kelvins
is still not defined in the global namespace, where values such as freezing_point
have been defined.
Why does Python work this way?
Well, as it turns out, the benefit of having a separate namespace for functions is that we can define a variable in the global namespace, such as temp_kelvins
and not need to worry about its name within a function, or the use of a function changing its value.
Inside the function, the value that is passed will be known as temp_kelvins
, but modifying that value will not alter a variable of the same name in the global namespace.
Let's have a look at another example using a modified kelvins_to_celsius()
function we can call kelvins_to_celsius2()
.
Here, we pass in a value as temperature
and modify the value that is passed in before returning it.
This is probably not a good idea in most cases because it could cause confusion, but it is perfectly valid code.
Let's now define a variable temperature
in the global namespace and use our function to modify it.
As you can see, the value of the variable temperature
in the global namespace was set to 303.15 and remains 303.15 after using the kelvins_to_celsius2()
function.
Although there is a variable inside that function with the same name as the value in the global namespace, using the function assigns the value of temperature
inside the function and manipulates that value only inside the function.
Caution: It is important to be aware that it is possible to access variable values that have been defined in the global namespace from within functions, even if the value has not been passed to the function. This is because Python will search for variables defined with a given name first inside the function, and then outside the function (the search domain is known as the variable's scope). If such a value is found then it can be used by the function, which could be dangerous!
Let's look at an example of behavior in a function that may be unexpected. Here we can define a third version of the kelvins_to_celsius()
function that we can call kelvins_to_celsius3()
.
You were perhaps expecting to see a value of 0
returned by kelvins_to_celsius3()
, but that does not occur because temp
is assigned temperature - 273.15
in the function.
Although temperature
was not passed to kelvins_to_celsius3()
it is defined in the global namespace and thus can be used by our example function.
Since temperature = 303.15
we get a value of 30.0 returned when using kelvins_to_celsius3()
.
Conclusion: Be careful!
For those who are interested, more information about namespaces and variables scopes can be found on the Real Python website.