In Python, functions are reusable pieces of code that can be called multiple times to perform a specific task. They help in making the code more organized, modular, and easier to maintain. In this tutorial, we will take a look at how to call functions in Python.
Step 1: Define a Function
Before calling a function, you need to define it. Functions in Python are defined using the def keyword followed by the function name and a pair of parentheses containing the input parameters if needed. The function body should be indented, and a colon should follow the parameter list.
Here’s an example of a simple function definition:
1 2 |
def greet(): print("Hello, World!") |
In this example, we defined a function called greet that prints “Hello, World!”.
Step 2: Call the Function
To call a function, you simply need to write its name followed by a pair of parentheses:
1 |
greet() |
This line of code calls the greet function, which results in the “Hello, World!” output.
Hello, World!
Step 3: Define a Function with Parameters
You can pass values to a function using parameters. In the function definition, you need to specify the parameter names inside the pair of parentheses. Here’s an example with a function that takes two parameters:
1 2 3 |
def add_numbers(a, b): result = a + b print(result) |
In this example, we defined a function called add_numbers that takes two parameters, a and b. Inside the function body, it calculates the sum of a and b and prints the result.
Step 4: Call a Function with Parameters
When calling a function with parameters, you need to provide the values for the parameters inside the pair of parentheses. For example, to call the add_numbers function:
1 |
add_numbers(3, 5) |
This line of code calls the add_numbers function and provides the values 3 and 5 for the parameters a and b. As a result, the function calculates the sum of 3 and 5 and prints it.
8
Full Code
1 2 3 4 5 6 7 8 9 10 |
def greet(): print("Hello, World!") greet() def add_numbers(a, b): result = a + b print(result) add_numbers(3, 5) |
Conclusion
In this tutorial, we showed you how to call functions in Python. We covered defining functions, calling them, and working with function parameters. Functions help make your code more organized and modular, making it easier to maintain, debug and understand.