Python Functions: The Basics
Functions are the backbone of any Python program. They help you structure your code, avoid repetition, and build modular, reusable solutions.
Whether you're a beginner or an experienced developer, you'll face important questions when working with Python functions. How do you properly pass arguments to a function? What are global variables and how do you work with them? Why do you need decorators and how do you use the global keyword? How can you return multiple values from a function?
Defining Python Functions: Syntax & Structure
What is a Function in Python?
A function is a named block of code that you can call repeatedly. In Python, functions are created using the def keyword.
Declaring and Calling Functions
Here's how you declare a function:
def greet():
print("Hello, world!")
You call a function by its name:
greet()
Python functions can contain various statements, conditionals, loops, and other language constructs. Defining functions properly helps you write clean, readable, and well-structured code.
Function Arguments in Python
Positional Arguments
Positional arguments are passed to a function in the order they are defined:
def greet(name):
print(f"Hello, {name}!")
greet("Anna")
When using positional arguments, it's important to maintain the correct order of parameters.
Default Arguments
Default arguments let you set parameter values that are used if no argument is passed:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
Using default arguments makes your functions more flexible and reduces the number of required parameters.
Keyword Arguments
Keyword arguments are passed with the parameter name explicitly specified:
def order(item, quantity):
print(f"You ordered {quantity} {item}(s)")
order(item="pizza", quantity=2)
Keyword arguments make your code more readable and allow you to pass parameters in any order.
Variable-Length Arguments
Python supports passing an arbitrary number of arguments using *args and **kwargs:
def summation(*args):
print(sum(args))
summation(1, 2, 3, 4) # 10
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=30)
The *args syntax accepts any number of positional arguments. The **kwargs syntax accepts any number of keyword arguments.
Returning Values from Python Functions
The Return Statement Basics
Functions can return results using the return statement. This lets you use the function's output elsewhere in your program:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
The return statement ends the function's execution and passes control back to the calling code.
Returning Multiple Values
Python allows you to return multiple values at once:
def get_coordinates():
return 10, 20
x, y = get_coordinates()
Technically, Python returns a tuple, which you can then unpack into separate variables. This is a convenient way to get multiple results from a single function.
Return Statement Nuances
If a function doesn't contain a return statement, it automatically