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:

  1. 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
  1. 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
  1. 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
  1. 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

Tags:

related content