Defining and Calling Functions in Python
What is a Function in Python?
A function in Python is defined using the def keyword, followed by:
-
The function name
-
A list of parameters inside parentheses
() -
An indented code block that forms the function’s body
Example: Simple Function
def greet(name, age):
"""Print a greeting with a name and age.""" # This is a docstring
print(f"{name} is {age} years old.")
# Calling the function
greet("Alice", 21)
Output:
Alice is 21 years old.
Explanation of the Example
-
Function Name:
greet -
Parameters:
nameandage -
Function Body: The indented
print()line -
Function Call:
greet("Alice", 21)
Here, we pass "Alice" and 21 as arguments to the greet function, which then executes and prints the greeting.
How Function Definition Works
-
The
defkeyword introduces the function. -
The first indented line can be a docstring (optional), which describes what the function does.
-
The rest of the indented code is the function body.
-
Defining a function creates a function object and assigns it to the function name.
You can even assign a function to another variable:
say_hello = greet
say_hello("Bob", 30)
How to Call a Function
To call a function:
-
Use its name followed by parentheses
() -
Pass arguments inside the parentheses if required
Example:
greet("Alice", 21)
Flow of Function Execution
When a function is called:
-
Python jumps to the function definition
-
Executes the body of the function
-
Returns control to the point where the function was called
Example: Function that Returns a Value
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
-
addis a function that returns the sum ofaandb -
add(5, 3)returns8, which we store inresultand print
Why Use Functions?
-
Avoid code repetition
-
Make programs more organized and modular
-
Improve code readability and reusability
