You've learned how to define functions, which are like recipes for specific tasks. But a recipe is useless if you never actually cook it! In this section, we'll explore how to 'call' or 'invoke' these functions, making them execute the code they contain and perform their intended actions.
Calling a function is straightforward. You simply use the function's name followed by a pair of parentheses (). If the function expects any input values (called arguments or parameters), you provide them inside these parentheses, separated by commas.
Let's start with a function that doesn't require any input and simply prints a message.
def greet():
print("Hello from the greet function!")
greet()In the code above, greet() is the function call. When Python encounters this line, it jumps to the greet function definition, executes the print statement, and then returns to where it left off after the function call.
Now, let's consider a function that takes arguments. These arguments are placeholders that receive the values you pass when you call the function.
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
greet_person("Bob")Here, greet_person is the function name. When we call greet_person("Alice"), the string "Alice" is passed as the value for the name parameter. Similarly, "Bob" is passed in the second call. Each call executes the function independently with its own provided argument.
What happens when a function is designed to return a value? This is where functions become incredibly powerful for calculations and data processing. The return statement is key.
def add_numbers(x, y):
sum_result = x + y
return sum_result
result = add_numbers(5, 3)
print(f"The sum is: {result}")
print(f"Another sum: {add_numbers(10, 2)}")