This lesson is partly based on the Software Carpentry group’s lessons on Programming with Python.
What is a function?¶
A function is a block of organized, reusable code that can make your scripts more effective, easier to read, and simple to manage.
You can think functions as little self-contained programs that can perform a specific task which you can use repeatedly in your code.
One of the basic principles in good programming is “do not to 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() command which is actually a built-in function in Python.
Anatomy of a function¶
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 data. Thus we might need to repeat such calculations quite frequently when analysing or comparing weather or climate data between the US and Europe, for example.
Let’s define our first function called
In : def celsiusToFahr(tempCelsius): ...: return 9/5 * tempCelsius + 32 ...:
The function definition opens with the keyword
deffollowed 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.
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
tempCelsiusin 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).
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 send your value to the required parameter(s) inside the parentheses:
In : freezingPoint = celsiusToFahr(0) In : print('The freezing point of water in Fahrenheit is:', freezingPoint) The freezing point of water in Fahrenheit is: 32.0 In : print('The boiling point of water in Fahrenheit is:', celsiusToFahr(100))