Function Calling

In Python, after defining a function, it needs to be called to execute the statements it contains. This concept is referred to as ‘function calling’.

Basic Function Calling

A function is called by using its name followed by parentheses (), sometimes enclosing arguments, if the function requires them.

Consider the following function that prints a greeting message:

1def print_greeting():
2    print("Hello, Codebay readers!")

You can call this function like so:

1print_greeting()  

Running the above code will output: Hello, Codebay readers!

Did you know?

Remember, the function must be defined before it is called, or Python will throw an error. Try to maintain the logical order in your code.

Function Calling with Arguments

When a function is designed to take arguments, values must be passed into the function during the call. These input values are referred to as arguments.

For instance, consider a function that adds two numbers:

1def add_numbers(a, b):
2    print(a + b)

We can call this function by providing two arguments:

1add_numbers(5, 3)  

This will output 8.

Caution

The number of arguments provided during the function call must correspond to the number of parameters defined in the function, or Python will throw an error.

Calling a Function from another Function

In Python, a function can be called from another function. This is useful for breaking down complex tasks into smaller, more manageable functions.

Consider a situation where we want to greet a user and then ask them a question:

 1def greet():
 2    print("Hello!")
 3  
 4def ask_question():
 5    print("How are you today?")
 6  
 7def converse():
 8    greet()
 9    ask_question()
10  
11converse()

In the above code, calling the converse() function will first execute the greet() function, printing out “Hello!” and then execute the ask_question() function, printing out “How are you today?”.

Function calling is a fundamental concept in Python, and it enhances code reusability and clarity. It’s a good practice to encapsulate repetitive or related tasks within a function and then call them as needed.