How to create and call a function in Python

About Python Function

In Python, a function is a block of reusable code that performs a specific task.

A function is defined outside of any class. It can be called independently.

A function can be called directly by its name.

A Python function may be created with parameters or without any parameters.

To create a function, you need to use the 'def' keyword before function name.

Create a function without parameter

1. Add the 'def' keyword followed by the function name welcome_message. You can choose your function name.

2. Add a parenthesis '()' and a colon ':' after the function name (welcome_message). They are the parts of the Python function syntax.
The code will look like this - def welcome_message():.

3. Now create a block of code that will be executed when the function will be called. The print message print("Welcome to xFactorSchool.com") is the block of code to be executed.
The block of code after the colon (:) must be indented consistently.

4. To call the function, just use the function name with parenthesis - welcome_message().

Please take a closer look at the following example:

Example of Python function without parameter

Output of the above example
Welcome to xFactorSchool.com

Live Code Playground

In the following Python code editor, you can practice by creating more functions and calling them. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output