Before understanding how to call a function in Python, let’s know what are functions. Functions are known as the block of statements used to carry out certain tasks while programming. They help us break a huge group of code into a block of modules. You can define functions anywhere & anytime in your code such as modules, classes or nested functions.
Let’s explore some function features of Python.
- Functions are used to avoid repeted code.
- Functions are used to convert a huge chunk of code into smaller modules.
- Functions help simplify the code and get a better understanding of modules.
- Helps create a reusable code which as save a considerate amount of memory.
- Function names are used to execute local functions written in the code.
- Functions in Python starts def followed by a colon (:) & a function name.
Rules to Define Python Function
- To declare and define a Python Function, ‘def‘ keyword is used.
- In Python, identifiers are used such as A-Z, a-z, & underscore (_).
- Using a (:) colon is mandatory while creating a Python function.
- Reserved word cannot be used as a function name or identifier while creating a Python function.
- Function parametes can be optionally empty or multiples in Python function.
How to Create a Function in Python
To create a function in Python, first, a def keyword is used to declare and write the function followed by the function name after the colon (:).
def function_name(): # use def keyword to define the function Statement to be executed return statement # return a single value.
Now let’s create a function in Python.
def myFun(): # define function name print(" Welcome to TechsTricks") myFun() # call to print the statement
Welcome to TechsTricks
How to Call a Function in Python
After creating a function in Python, here’s how you can call it: function_name() or other function or nested function. Here’s a syntax for calling a Python function.
def function_name(): Statement1 function_name() #directly call the function #calling function using built-in function in Python def function_name(): str = function_name('arjun') #assign the function name to call the function print(str) #print the statement
Here’s how you can create a welcome message using functions in Python.
def MyFun(): print("Hello World") print(" Welcome to the TechsTricks") MyFun() #Call Function to print the message.
Hello World Welcome to TechsTricks
In the above example, we’ve called the main function to print the statement. We hope now you understand how to call a function in Python. Up next, you can read about how to take User Input in Python.