×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Different ways to define and call user-defined functions

By IncludeHelp Last updated : December 08, 2024

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

Comments and Discussions!

Load comments ↻





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