(toc)
In Python, a function is a block of reusable code that performs a specific task. Functions allow you to break down your program into smaller, more manageable pieces, making it easier to read, maintain, and reuse code. Functions are one of the most important concepts in Python programming.
Defining a Function
You define a function in Python using the def
keyword, followed by the function name, parentheses ()
, and a colon :
. The code inside the function is indented.
Basic Syntax:
def function_name(parameters): # Code block return value
def
: Keyword used to define a function.function_name
: The name you give to your function.parameters
: Optional values you pass into the function.return
: Optional statement used to send back a result.
Example: A Simple Function
def greet(): print("Hello, World!") # Calling the function greet() # Output: Hello, World!
In this example, greet()
is a function that doesn’t take any parameters and simply prints a greeting message.
Function Parameters
Functions can take parameters (also called arguments), which allow you to pass information into the function. You can define a function with any number of parameters or without any parameters at all.
Example: Function with Parameters
def greet(name): print(f"Hello, {name}!") # Calling the function with an argument greet("Alice") # Output: Hello, Alice! greet("Bob") # Output: Hello, Bob!
In this example, name
is a parameter. When calling the function, we pass the value "Alice"
or "Bob"
as an argument.
Return Statement
The return
statement allows a function to return a value back to the caller. If no return
is specified, the function will return None
by default.
Example: Function with a Return Value
def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8
Here, the add()
function takes two parameters, a
and b
, adds them, and returns the result.
Multiple Return Values
A function can return multiple values by separating them with commas. Python will return these values as a tuple.
Example: Function with Multiple Return Values
def get_name_age(): return "Alice", 30 name, age = get_name_age() print(name) # Output: Alice print(age) # Output: 30
In this example, the function returns two values, a string and an integer. When we call the function, we can assign the returned values to multiple variables.
Keyword Arguments
Python allows you to pass arguments by their names rather than their position. This is called keyword arguments.
Example: Keyword Arguments
def greet(name, age): print(f"Hello, {name}! You are {age} years old.") # Calling the function using keyword arguments greet(name="Alice", age=25) greet(age=30, name="Bob") # The order of arguments does not matter
In this example, we specify the parameter names when calling the function, making the code clearer and more flexible.
Default Arguments
You can define default values for function parameters. If an argument is not provided when calling the function, the default value will be used.
Example: Function with Default Arguments
def greet(name, age=20): print(f"Hello, {name}! You are {age} years old.") greet("Alice") # Output: Hello, Alice! You are 20 years old. greet("Bob", 25) # Output: Hello, Bob! You are 25 years old.
Here, age
has a default value of 20
. If the caller does not provide a value for age
, it will automatically use the default.
Variable-Length Arguments
Sometimes, you may not know how many arguments you will receive. You can use variable-length arguments to handle an arbitrary number of arguments.
*args
: Collects non-keyword arguments into a tuple.**kwargs
: Collects keyword arguments into a dictionary.
Example: Using *args
def print_numbers(*args): for number in args: print(number) print_numbers(1, 2, 3) # Output: 1, 2, 3 print_numbers(10, 20) # Output: 10, 20
In this example, *args
allows the function to accept any number of positional arguments, which are collected into a tuple.
Example: Using **kwargs
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=30, city="New York") # Output: # name: Alice # age: 30 # city: New York
Here, **kwargs
allows the function to accept any number of keyword arguments, which are collected into a dictionary.
Lambda Functions
A lambda function is a small anonymous function defined using the lambda
keyword. It’s often used for short, throwaway functions that are used only once or twice.
Syntax:
lambda arguments: expression
Example: Lambda Function
multiply = lambda x, y: x * y result = multiply(3, 4) print(result) # Output: 12
Here, the lambda function takes two arguments, x
and y
, and returns their product.
Recursion
A recursive function is a function that calls itself in order to solve a problem. Recursion is often used for problems that can be broken down into smaller subproblems.
Example: Factorial Function (Recursion)
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) result = factorial(5) print(result) # Output: 120
In this example, the function factorial()
calls itself to compute the factorial of a number. The base case is when n == 0
, returning 1.
Function Scope
Variables defined inside a function are in the local scope of that function, and cannot be accessed outside of it. Variables defined outside of functions are in the global scope.
Example: Local and Global Variables
x = 10 # Global variable def example_function(): x = 5 # Local variable print(f"Local x: {x}") example_function() # Output: Local x: 5 print(f"Global x: {x}") # Output: Global x: 10
In this example, the variable x
inside the function is different from the global x
.