Python: How to use functions in Python? The Tutorial you need!

A function in Python is a block of code that performs a specific task. Functions are used to avoid repetitive code and to improve the code's organisation and readability. We are going to cover the following aspect in this tutorial: the fundamentals of creating and using Python functions. How to define and use a Python function without parameters, how to define and use a Python function with parameters, and how to define and use a Python function with default parameters.    

Defining a Python Function

We defined a function by using the keyword “def”, followed by the function’s name and then the parentheses. We can include parameters (or arguments) that the function will use to perform its task inside the parentheses. The code that will be executed when the function is called is then indented in the function body.

Example: Python function which adds two numbers and returns the sum.

In the code snippet below, the function add_numbers takes two parameters, x and y. It then sums up the two parameters and returns the result.

Calling the function: How to call and use the function in code?

In Python, we simply type the function name followed by the arguments (if any were defined) inside parentheses to call a function. Here's an example of how to use the add_numbers function which we defined earlier:

 

So, in the code snippet below, we called the add_numbers function and provides the arguments: 5 and 6. The function returns the sum of the arguments, which are saved in the variable sum. Then, the value of the sum is then printed out, which is 11.

 

Don’t be confused with the word “parameters” and “arguments” in functions.

Parameters: A named variable that appears in the function definition is referred to as a parameter. It serves as a placeholder for the value that will be passed to the function when it is called. For example, x and y are parameters in the following function definition:

add_numbers(x, y)

 

Argument: An argument is the actual value passed to the function when it is called. In the following example, the arguments passed to the add_numbers () function are 5 and 6: add_numbers (5,6)

Don’t worry about this too much at this stage, just understand the difference between parameters and arguments. Things will appear clearer as we move on.

Functions Without Any Parameters

Functions with no parameters are those that do not accept any arguments. These functions are useful when you need to perform a task that does not require user input. We simply use empty parentheses after the function name to define a function with no parameters.

Example 1

An example could be a function that prints a greeting message as follows.

The code snippet below is an example of a function that prints a greeting message, for instance, a greeting message when you visit a website.

  

Example 2

Let’s look at another real-life practical example. In the code snippet below, we define a function called get_weather (). This get_weather () function accepts no parameters. It makes a GET request to the OpenWeatherMap API and retrieves the current weather data for New York using the requests module. The weather data is then formatted into a string and sent to users via email or push notification. For this code to work in the real world we must the dummy API Key; “YOUR_API_KEY” with your own OpenWeatherMap API key.

 

Functions With Parameters

Functions with parameters are those that accept one or more arguments. These functions are useful when performing a task that requires user input. We include the parameter names in parentheses after the function name to define a function with parameters.

Example 1:

A function that takes two numbers and returns the sum as we saw above.

Example 2: A function that calculates loan payments.

In the code snippet below, the loan_amount, interest_rate, and payment_period parameters are passed to the calculate_loan_payment () function. It then applies the monthly loan payment formula to return the monthly payment amount. The main programme then calls the function with example parameter values and prints out the monthly payment amount as shown below.

Functions With Default Parameters

Functions with default parameters accept one or more arguments, with some of the arguments having default values. When the user does not provide a value for that argument, these default values are used. To define a function with default parameters, we include the default values in the function definition after the parameter names.

Example 1:

An example could be a function that accepts a name and a greeting message as default parameters: A real-life use case could be an email service that adds a default signature to all emails sent by the user.

In the code snippet below, the function greet accepts two parameters: name and greeting. If no value is specified for greeting, "Hello" is used as the default. Then, the greeting and name are then printed by the function.

Example 2

A healthcare platform that allows patients to schedule doctor appointments. A Python function with default parameters can be used to take in the patient's preferred doctor, date, and time for the appointment, with the current date and time serving as the default. This function can help patients who want to schedule an appointment quickly without specifying a specific date and time to simplify the process.

In the code snippet below, the function schedule_appointment () accepts two parameters, doctor_name and preferred_ date, and one default parameter, preferred_time. The function defaults time is set to 10:00 AM if the preferred_time parameter is not specified. The function then prints a message that includes the doctor's name, appointment date, and time. To demonstrate to you the use of the default parameter, the main programme calls the function twice with different parameter values.

More Python functions use case.

A function that allows a customer to pick a product, add it to the cart, and calculate the total price:

Let’s explain the code snippet below.

Products and prices are lists that contain the names and prices of available products, a cart is a list that contains the items the customer has added to their cart, and the item is the name of the product the customer wants to add to this function.

How does the function work?

The function first determines whether the item is present in the list of available products. If it is not, the function returns the current cart without adding the item and prints a message: “Sorry, we don't have that item”. If the item is available, the function locates its index in the products list and adds it to the cart using the append () method. The function then computes and prints the total price of the items in the cart, including the newly added item, as well as the current cart and total price. Finally, the function returns the total price and the updated cart.