Home »
Python
Python Different ways to define and call user-defined functions
Last Updated : April 22, 2025
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.
Example
In the below example, we are defining a function hi() that prints "Hi" and then calling the function to execute the print statement:
#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.
Example
In the below example, we are calling the function hi() before it is defined, which will result in an error, as functions must be defined before calling them in Python:
# 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.
Example
In the below example, we are defining a function hi() that prints "Hi", and then calling it inside the main() function. The main() function is executed, which in turn calls hi(), and the output is "Hi":
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.
Example
In the below example, we are defining the main() function to call the hi() function, and then using the if __name__ == "__main__": construct to ensure that the main() function is only called when the script is executed directly:
def main():
hi()
def hi():
print("Hi")
if __name__=="__main__":
main()
Output
Hi
Python Define and Call Function Exercise
Select the correct option to complete each statement about defining and calling functions in Python.
- In Python, you define a function using the ___ keyword followed by the function name and parameters.
- To call a function in Python, you use the function's ___ followed by parentheses.
- When calling a function, if it has parameters, you must pass the ___ that match the order and type of the parameters.
Advertisement
Advertisement