= [5, 6, 7]
numbers sum(numbers)
18
We have already seen some built-in functions: e.g. print
, type
, len
. And we have seen special functions that belong to a variable (python object) like my_dict.items()
and my_list.append()
. There are more built-in functions e.g. for mathematical operations:
= [5, 6, 7]
numbers sum(numbers)
18
The Python Documentation at docs.python.org has more info about built-in functions.
We will now turn to writing own functions. When should you write your own function?
A big advantage of not having duplicate code inside your script or in multiple scripts is that when you want to make a slight modification to a function, you only have to do this modification in one place, instead of multiple lines that are doing more or less similar things.
Python provides for this by letting us define things called ‘functions’. Let’s start by defining a function fahr_to_celsius that converts temperatures from Fahrenheit to Celsius:
def fahr_to_celsius(temp_fahrenheit):
= (temp_fahrenheit - 32) * (5/9)
temp_celsius return temp_celsius
The function definition opens with the keyword def
followed by the name of the function fahr_to_celsius
and a parenthesized list of variables (in this case only one temp_fahrenheit
). The body of the function — the statements that are executed when it runs — is indented below the definition line. The body concludes with a return
keyword followed by the return value.
When we call the function, the values we pass to it as arguments are assigned to the variables in the function definition so that we can use them inside the function. Inside the function, we use a return statement to send a result back to whoever asked for it.
Let’s try running our function.
98) fahr_to_celsius(
36.66666666666667
print('freezing point of water:', fahr_to_celsius(32), 'C')
print('boiling point of water:', fahr_to_celsius(212), 'C')
freezing point of water: 0.0 C
boiling point of water: 100.0 C
Here we directly passed a value to the function. We can also call the function with a variable:
= 0
a print(fahr_to_celsius(a))
-17.77777777777778
What happens if you pass a variable name that is not defined yet?
print(fahr_to_celsius(b))
NameError: name 'b' is not defined
Exercises
Now go back to your browser to morning_exercises.ipynb and continue with exercises 8 and 9.
When you finished the exercises, continue to the afternoon session