Home »
Python
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:
- Define first and then call
- Calling before define
- Function calling inside another function
- 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