Functions: Arguments and Parameters
A deeper dive into function arguments, including positional, keyword, and default arguments. Understand variable scope within functions.
Python Functions and Arguments
Functions in Python
A function is a block of organized, reusable code that performs a specific task. Functions help break down complex tasks into smaller, more manageable pieces, making your code more readable, maintainable, and reusable. In Python, functions are defined using the def
keyword.
Here's the basic structure of a Python function:
def function_name(parameters):
# Code to be executed
return value # Optional return statement
Key aspects of a function:
- Definition: Declaring a function with the
def
keyword. - Name: A unique identifier for the function (
function_name
). - Parameters: Optional input values passed to the function (
parameters
). - Body: The code block that performs the function's task.
- Return Value: An optional value that the function sends back to the caller using the
return
statement. If noreturn
statement is present, the function returnsNone
by default.
Arguments and Parameters
Parameters are variables listed inside the parentheses in the function definition. They act as placeholders for the values that will be passed into the function.
Arguments are the actual values passed to the function when it is called. These values are assigned to the corresponding parameters within the function.
Think of it this way: Parameters are like labels in the function definition, while arguments are the actual data that gets plugged into those labels when the function is used.
Example:
def greet(name): # 'name' is the parameter
print(f"Hello, {name}!")
greet("Alice") # "Alice" is the argument
greet("Bob") # "Bob" is the argument
A Deeper Dive into Function Arguments
Python provides several ways to pass arguments to functions, offering flexibility and control.
Positional Arguments
Positional arguments are passed to a function based on their order. The first argument is assigned to the first parameter, the second argument to the second parameter, and so on.
Example:
def describe_person(name, age, city):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
describe_person("Charlie", 30, "London") # Positional arguments
Important: The order matters! Swapping the order of the arguments will lead to incorrect results.
Keyword Arguments
Keyword arguments are passed to a function with a specific name associated with each value. This allows you to pass arguments in any order, as long as you specify the parameter name.
Example:
def describe_person(name, age, city):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
describe_person(age=25, name="David", city="New York") # Keyword arguments
Default Arguments
You can assign default values to parameters in a function definition. If a caller doesn't provide a value for that parameter, the default value will be used.
Example:
def greet(name, greeting="Hello"): # 'greeting' has a default value
print(f"{greeting}, {name}!")
greet("Eve") # Uses the default greeting: "Hello, Eve!"
greet("Frank", "Hi") # Overrides the default greeting: "Hi, Frank!"
Important: Default arguments must be defined after positional arguments in the function definition.
Combining Argument Types
You can combine positional, keyword, and default arguments. However, positional arguments must come first, followed by keyword arguments. Remember, any argument passed *after* a keyword argument must *also* be a keyword argument.
Example:
def describe_item(name, price, quantity=1, currency="$"):
print(f"Item: {name}")
print(f"Price: {currency}{price}")
print(f"Quantity: {quantity}")
describe_item("Book", 20) # name (positional), price (positional), quantity (default), currency (default)
describe_item("Pen", 2, quantity=10) # name (positional), price (positional), quantity (keyword), currency (default)
describe_item("Laptop", 1200, currency="€") # name (positional), price (positional), quantity (default), currency (keyword)
describe_item("Charger", 30, quantity=2, currency="£") # name (positional), price (positional), quantity (keyword), currency (keyword)
# This will raise an error (positional argument after keyword argument)
# describe_item("Keyboard", quantity=1, 50)
Variable Scope within Functions
Variable scope refers to the region of a program where a variable can be accessed. In Python, the scope of a variable depends on where it is defined.
Local Scope: Variables defined inside a function have local scope. They can only be accessed within that function. Once the function finishes executing, these variables are destroyed.
Global Scope: Variables defined outside of any function have global scope. They can be accessed from anywhere in the program, including inside functions.
Example:
global_variable = 10 # Global scope
def my_function():
local_variable = 5 # Local scope
print(f"Inside function: global_variable = {global_variable}")
print(f"Inside function: local_variable = {local_variable}")
my_function()
print(f"Outside function: global_variable = {global_variable}")
# print(f"Outside function: local_variable = {local_variable}") # This will cause an error because local_variable is not accessible here
def modify_global():
global global_variable # Use 'global' to modify the global variable
global_variable = 20
print(f"Inside modify_global: global_variable = {global_variable}")
modify_global()
print(f"Outside after modify_global: global_variable = {global_variable}")
Key Points:
- If you try to access a local variable outside its function, you'll get a
NameError
. - If you want to modify a global variable inside a function, you need to use the
global
keyword. Without it, Python will create a new *local* variable with the same name, rather than modifying the global one.