Let's create a simple function that calculates the area of a rectangle:
def calculate_rectangle_area(length, width):
return length * width
# Calling the function with arguments
area = calculate_rectangle_area(5, 10)
print("Area:", area)
In this example, length
and width
are parameters. We pass 5
and 10
as arguments when calling the function. The result (50) is then printed to the console.
What causes it:
def calculate_rectangle_area(length, width):
print("Area:", length * width)
# No arguments provided when calling the function
calculate_rectangle_area()
Error message:
Traceback (most recent call last):
File "example.py", line 4, in <module>
calculate_rectangle_area()
NameError: name 'length' is not defined
Solution:
def calculate_rectangle_area(length=1, width=1):
print("Area:", length * width)
# No arguments provided when calling the function
calculate_rectangle_area()
Why it happens: The default values for length
and width
are set to 1. If no arguments are passed, Python throws a NameError because the variables have not been assigned any value.
How to prevent it: Always ensure that you provide the required arguments when calling functions with no default values, or set default values for your parameters as shown above.
What causes it:
def calculate_rectangle_area(length, width):
return length * width
# Incorrect argument types provided
calculate_rectangle_area("5", "10")
Error message:
Traceback (most recent call last):
File "example.py", line 4, in calculate_rectangle_Area
return length * width
TypeError: unsupported operand type(s) for *: 'str' and 'str'
Solution:
def calculate_rectangle_area(length, width):
if not isinstance(length, (int, float)):
raise TypeError("Length must be a number.")
if not isinstance(width, (int, float)):
raise TypeError("Width must be a number.")
return length * width
Why it happens: Strings cannot be multiplied; only numbers can. We pass two string arguments to our function, causing the TypeError.
How to prevent it: Ensure that your function accepts only appropriate data types as arguments. In this case, we check if the provided values are of type int
or float
. If not, we raise a custom error message.
What causes it:
def greet(name, age):
print("Hello! My name is", name)
# Incorrect order of arguments when calling the function
greet("Alice", 30)
Error message: None (No error occurs, but the output may not be what you expect.)
Solution:
def greet(name, age):
print("Hello! My name is", name)
# Using keyword arguments to specify argument order
greet(age=30, name="Alice")
Why it happens: Python allows you to pass arguments in any order as long as you use keyword arguments. In our example, name
and age
are swapped when calling the function, so the output is not what we intended.
How to prevent it: Always ensure that you pass arguments in the correct order unless using keyword arguments explicitly.