After reading this article, you will be able to:
• What are functions, and how are they defined?
• What are the parameters and arguments
• How to return values from functions
• How to define a function documentation
• What represents the scope in Python
• What are keyword arguments
• Flexible and Default arguments
• What are the Python exceptions and how to handle and how to raise them
• Assert Statements
Introduction
A function is a reusable, well-organized piece of code that performs a certain task. Functions enable us to keep our code clean while also allowing us to reuse it.
Built-in Functions
Python comes with a number of built-in functions that are always available. Print and max are two of these functions. Let's look at some examples of how we can apply them.
Objects are accepted and printed by the print function.
print("Python")
print("chess", "backgammon")
Output:
Python
chess backgammon
The max function accepts an iterable and returns the largest item
numbers = [10, 5, 49, 24, -10]
largest_number = max(numbers)
largest_number
Output:
49
We simply call the function by writing its name and pass the required inputs
User-Defined Functions
As a programmer or data scientist, we occasionally require functionality that is customized to our requirements. We can define our own functions in these situations.
To define a function, we must adhere to the following guidelines:
1. Use the keyword def to introduce a function definition
2. Write the function name followed by parentheses () and a colon:
3. Define a list of parameters inside these parentheses (optional)
4. Write the function body. The statements that form the function body, start at the next line and must be intended. When the function is called the code in the function body is run.
5. The first statement of the function body can be a string literal which represents the function documentation (optional)
6. Use the return keyword to pass back a result to the caller (optional)
If you believe there are a lot of steps, don't worry. Many instances will be shown, and the concepts will become clear.
Defining a Function Without Parameters
Let's look at a simple function definition that doesn't include any optional elements. We can use parenthesis () to call the function by typing its name . The current date will be printed when we call this function.
#Defining a Function Without Parameters
import datetime # importing the "datetime" module
def print_current_date():
current_date = datetime.datetime.now().date()
print(current_date)
print_current_date()
Output
2021-08-03
Please keep in mind that your results may vary. The date you executed the function will be the output.
Defining a Function With Parameters
We need function parameters almost always. They’re used when we want to pass data into our function. When we call a function we pass arguments (values for the parameters) to the function.
One Parameter Example
def print_message(text):
print(text)
print_message("Forgive yourself for your faults and your mistakes and move on. - Les Brown")
output:
Almost all of the time, we require function parameters. When we need to provide data into a function, we use them. Arguments (parameter values) are passed to a function when it is called.
It's essential when defining parameters like that. We'll get an error if we don't pass an argument value for this parameter.
def print_message(text):
print(text)
print_message()
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-f2f093834d71> in <module>()
2 print(text)
3
----> 4 print_message()
TypeError: print_message() missing 1 required positional argument: 'text'
We'll look at how to define optional arguments later in this article (arguments with a default value).
Multiple Parameters Example
We can add as many parameters as we want and, as long as we use commas to separate them. In many circumstances, more than one parameter is required.
The order in which the arguments are given matches to the order in which our function's parameters are defined. In the example below, the number1 parameter is set to 10 and the number2 parameter is set to 5.
def sum_numbers(number1, number2):
print(number1 + number2)
sum_numbers(10, 5)
Output:
15
However, because our function just prints the result and does not utilize a return statement, we cannot save the value in a variable using the above function definition. Let's have a look at what happens if we attempt to save the result.
def sum_numbers(number1, number2):
print(number1 + number2)
result = sum_numbers(10, 5)
print(result)
Output:
15
None
Because our function was called, the sum is printed, but the result variable has a value of None instead of 15. Let's look at how we can return values in the next part.
Defining a Function That Returns a Result
The return keyword can be used to exit the current function call and return a desired result. Let's look at how we may re-define sum numbers to return the sum rather than printing it.
def sum_numbers(number1, number2):
return number1 + number2
result = sum_numbers(10, 5)
print(result)
Output:
15
The result variable has a value of 15 this time, as we can easily see.
Defining a Function That Returns Multiple Values
We can also define a function that returns multiple values. We can do that by constructing objects called tuples in your function. The tuples data type in Python is an immutable sequence. This means that they can contain multiple values like lists.
import datetime
def get_current_datetime():
current_datetime = datetime.datetime.now()
current_date = current_datetime.date()
current_time = current_datetime.time()
return (current_date, current_time)
date, time = get_current_datetime()
print(date)
print(time)
Output:
2021-08-03
18:08:43.049105
Sequence unpacking is used in the example above. The values from the tuple are simply "unpacked" into date and time variables.
Top comments (0)