Create and Call Functions in Python
Functions are reusable blocks of code that perform a specific task. They help organize your code, make it more readable, and avoid repetition. In this tutorial, we’ll learn how to create and call functions in Python.
Understanding Function Basics
A function definition in Python looks like this:
def function_name(parameters):
# Code to be executed
return value
Let’s break this down:
def: This keyword indicates that you are defining a function.function_name: This is the name you choose for your function. It must follow Python’s naming rules.(parameters): These are the inputs that the function receives. They are optional.:: This colon marks the beginning of the function’s code block.# Code to be executed: This is the code that the function performs.return value: This specifies the value that the function returns to the caller. If there’s noreturnstatement, the function implicitly returnsNone.
Example 1: A Simple Function with No Parameters
Let’s create a function that displays a greeting.
def greet():
print("Hello, world!")
print("Welcome to Python!")
Now, let’s call this function:
greet()
Explanation: We define a function named greet that doesn’t take any input parameters. Inside the function, we use the print function to display two messages. When we call greet(), the code inside the function is executed, and the output is displayed on the console.
Common mistake: Forgetting the parentheses after greet when calling the function. This results in a syntax error.
# Incorrect: greet
# greet
# Correct: greet()
Output:
Hello, world!
Welcome to Python!
Example 2: A Function with Parameters (Math Calculation)
Now, let’s create a function that calculates the area of a rectangle. This function will take the length and width as parameters.
def calculate_rectangle_area(length, width):
area = length width
return area
Let’s call the function with some values:
result = calculate_rectangle_area(5, 10)
print(f"The area is: {result}")
Explanation: We define a function named calculate_rectangle_area that takes two parameters: length and width. Inside the function, we calculate the area by multiplying the length and width. The return statement returns the calculated area. When we call the function with 5 and 10, the area is calculated as 50, and this value is stored in the result variable. Finally, we print the result using an f-string.
Common mistake: Not providing values for the parameters when calling the function. This will cause a TypeError because the function expects two arguments.
# Incorrect: calculate_rectangle_area(5)
# TypeError: calculate_rectangle_area() missing 1 required positional argument: 'width'
# Correct: calculate_rectangle_area(5, 10)
Output:
The area is: 50
Example 3: A Function with a Return Value and Error Handling
Let’s create a function that calculates the square root of a number, but it includes error handling for negative inputs.
import math
def calculate_square_root(number):
if number < 0:
return "Cannot calculate the square root of a negative number."
else:
result = math.sqrt(number)
return result
Let’s call the function with different inputs:
print(calculate_square_root(9))
print(calculate_square_root(-4))
print(calculate_square_root(16))
Explanation: We import the math module to use the math.sqrt() function. The function takes a single parameter, number. It first checks if the number is negative. If it is, it returns an error message. Otherwise, it calculates the square root using math.sqrt() and returns the result. This demonstrates basic error handling.
# Incorrect: calculate_square_root(-4)
# Output: Cannot calculate the square root of a negative number.
# Correct: calculate_square_root(9)
# Output: 3.0
# Correct: calculate_square_root(-4)
# Output: Cannot calculate the square root of a negative number.
# Correct: calculate_square_root(16)
# Output: 4.0
Output:
3.0
Cannot calculate the square root of a negative number.
4.0



Leave a Reply