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:
You can call this function like so:
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:
We can call this function by providing two arguments:
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:
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.