In Python, required arguments are parameters that must be provided with a value when calling a function. These arguments are defined in the function’s parameter list and are necessary for the function to execute correctly.
You can define functions with required arguments using the following syntax:
def function_name(arg1, arg2, ...):
# Function body
function_name
: This is the name of the function you are defining.arg1, arg2, ...
: These are the required arguments (also known as parameters) of the function. You can specify multiple arguments separated by commas.
If a required argument is not provided, Python will raise a TypeError
and indicate that the function was called with missing arguments.
Required Arguments in Python example
Here’s an example of a Python function with required arguments:
def calculate_rectangle_area(length, width):
area = length * width
print(f"The area of the rectangle is: {area}")
calculate_rectangle_area(5, 3)
calculate_rectangle_area(5)
Output:
If you omit either the length
or width
argument or provide them in the wrong order, you will encounter an error.
Let’s consider a function called calculate_bmi
that calculates the Body Mass Index (BMI) given a person’s weight and height:
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi:.2f}")
In this example, the calculate_bmi
function takes two required arguments: weight
and height
. It calculates the BMI by dividing the weight (in kilograms) by the square of the height (in meters). The calculated BMI is then printed with two decimal places.
To use this function, you need to provide values for both weight
and height
when calling it:
calculate_bmi(70, 1.75)
The function call above will output:
Your BMI is: 22.86
If you omit either the weight
or height
argument, you will encounter an error:
calculate_bmi(70) # Raises TypeError: calculate_bmi() missing 1 required positional argument: 'height'
Do comment if you have any doubts or suggestions on this Python Function topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.