Python | Different ways to define and call user-defined functions

Python function definitions and calling: Here, we are going to learn the different ways to declare define and call a function. By Pankaj Singh Last updated : December 30, 2023

The following are the different ways to define and call a user-defined function:

  1. Define first and then call
  2. Calling before define
  3. Function calling inside another function
  4. Define main as starting point

1. Define first and then call

The standard way to define and call a function in Python is to first write the function definition and then use it wherever you want.

#Function Defination
def hi():
    print("Hi")

#Function Calling
hi()

Output

Hi

2. Calling before define – but it will not work

If you call a function before defining it will generate a NameError. This is of defining and calling a function is incorrect.

# Function Calling
hi()

# Function Definition
def hi():
    print("Hi")

Output

    hi()
NameError: name 'hi' is not defined	

3. Function calling inside another function

A function can also be called inside another function.

def main():
    hi()

def hi():
    print("Hi")

main()

Output

Hi

4. Define main as starting point

You can also define a function as starting calling function in Python. This example shows how you can define a function as the starting point.

def main():
    hi()

def hi():
    print("Hi")

if __name__=="__main__":
    main()

Output

Hi

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.