A function is a block of code that is organized, reusable, and performs a single, related action. Functions are essential for following the DRY (Don’t Repeat Yourself) principle.
1. Defining and Calling Functions
A. Defining a Function
You define a function using the def keyword, followed by the function name, parentheses (), and a colon :. The code block (the function body) must be indented.
# Function Definition
def greet_user():
"""Prints a simple greeting."""
print("Welcome to Python!")
- Note: The string enclosed in triple quotes (
"""...""") is the function’s docstring (P1.2), which documents its purpose.
B. Calling a Function
To execute the code inside the function, you must call it by using its name followed by parentheses.
# Function Call
greet_user()
# Output: Welcome to Python!
2. Arguments and Parameters
Parameters are the names defined in the function definition. Arguments are the actual values passed to the function when it is called.
A. Positional Arguments
Arguments are passed based on their order (position) in the function call.
def add_numbers(num1, num2): # num1 and num2 are parameters
result = num1 + num2
print(result)
add_numbers(10, 5) # 10 and 5 are arguments
# Output: 15
B. Keyword Arguments
You can specify arguments by the parameter name during the function call. This is helpful for clarity and allows you to pass arguments out of order.
add_numbers(num2=5, num1=10)
# Output: 15 (Order doesn't matter when keywords are used)
3. Default Arguments
You can specify a default value for a parameter in the function definition. If the caller does not provide an argument for that parameter, the default value is used.
Rule: Any parameter with a default value must be defined after all non-default (required) parameters.
def greet_person(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet_person("Alice") # Uses default greeting
# Output: Hello, Alice!
greet_person("Bob", "Good morning") # Overrides default
# Output: Good morning, Bob!
4. The return Statement
The return statement is used to send a value (or values) back to the line of code that called the function.
- Purpose: Functions that perform calculations or fetch data should use
return. - Flow Control: When
returnis executed, the function immediately terminates. If no value is explicitly returned, the function implicitly returnsNone.
def multiply(a, b):
return a * b # Returns the product
# The result is stored in the 'product' variable
product = multiply(4, 6)
print(product)
# Output: 24
5. Variable Scope
Scope refers to the region of the code where a variable is accessible.
A. Local Scope
Variables defined inside a function are local to that function. They cannot be accessed from outside the function.
def my_function():
local_var = 5
print(local_var) # Accessible inside the function
my_function()
# print(local_var) # Error: NameError (local_var is not defined outside)
B. Global Scope
Variables defined at the top level of a script (outside any function) are global and can be accessed by any part of the program, including functions.
global_var = 10 # Defined globally
def another_function():
# Can read the global variable
print(global_var)
another_function()
# Output: 10
