Different ways to call a function in Python
Published on Aug. 22, 2023, 12:16 p.m.
There are several ways to call a function in Python, including:
- Using the function name followed by parentheses: This is the most common way to call a function in Python. Here’s an example:
def my_function():
print("Hello, World!")
my_function() # call the function
- Calling a function using a variable: You can also assign a function to a variable and then call that variable as a function. Here’s an example:
def my_function():
print("Hello, World!")
function_variable = my_function # assign function to variable
function_variable() # call the function through the variable
- Calling a function using arguments: You can pass arguments to a function when calling it. Here’s an example:
def my_function(name):
print("Hello, " + name + "!")
my_function("John") # call the function with an argument
- Calling a function inside another function: You can call one function from another function. Here’s an example:
def inner_function():
print("Hello from the inner function!")
def outer_function():
print("Hello from the outer function!")
inner_function() # call the inner function
outer_function() # call the outer function