What Does It Mean to Call a Function?
In programming, a function call
refers to executing a pre-defined function to perform a specific task.
Basic Structure of a Function Call
In Python, you call a function using the function's name and parentheses.
You can place arguments inside the parentheses if needed.
def greet(name):
print(f"Hi, {name}!")
# Function call
greet("Friend")
In the code above, the function greet
is called by placing parentheses ()
after the function name.
The value "Friend"
passed inside the parentheses is used as an argument for the name
parameter inside the function.
The function prints "Hi, Friend!" to the screen using the print statement.
What if You Don't Have Any Arguments to Pass to a Function?
If there are no values to pass to the function, you simply use the parentheses without any arguments.
def say_hello():
print("Hello")
# Function call without arguments
say_hello()
In the code above, the say_hello
function does not take any arguments and prints "Hello" every time it is called.
Function Calls with return
Keyword to Return Results
A function can return a result using the return
keyword after completing its task.
The returned result can be stored in a variable or used in further operations.
# Function to calculate the area of a rectangle
def calculate_rectangle_area(width, height):
# Return the product of width and height
return width * height
# Calculate the area of a rectangle with width 3 and height 4 and store the result in 'result' variable
result = calculate_rectangle_area(3, 4)
# Print 12
print(result)
In the code above, the calculate_rectangle_area
function takes two arguments, width
and height
, calculates the area of the rectangle, and returns the result.
Calling the function with calculate_rectangle_area(3, 4)
returns the result and stores it in the result
variable.
Later, the value is printed using print(result)
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.