Functions are reusable blocks of code designed to perform specific tasks. They help in organizing code, improving readability, and reducing redundancy.
1. Defining a Function
Functions are defined using the def
keyword followed by the function name and parentheses.
def greet():
print("Hello, world!")
Calling a Function
To execute the code inside a function, you “call” it by using its name followed by parentheses:
greet() # Output: Hello, world!
2. Function Arguments
Functions can accept data as input (called arguments) and operate on it.
Positional Arguments
Arguments passed in order:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Default Arguments
You can assign default values to parameters:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
Keyword Arguments
Specify arguments by name for clarity:
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet(last_name="Doe", first_name="John") # Output: Hello, John Doe!
Variable-Length Arguments
*args
: For any number of positional arguments:pythonCopy codedef add(*numbers): return sum(numbers) print(add(1, 2, 3)) # Output: 6
**kwargs
: For any number of keyword arguments:pythonCopy codedef display_info(**info): for key, value in info.items(): print(f"{key}: {value}") display_info(name="Alice", age=25) # Output: # name: Alice # age: 25
3. Return Statement
The return
keyword is used to send back a result from a function.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
Functions can return multiple values as a tuple:
def arithmetic_operations(a, b):
return a + b, a - b, a * b, a / b
sum_, diff, prod, quot = arithmetic_operations(10, 2)
print(sum_, diff, prod, quot) # Output: 12 8 20 5.0
4. Scope of Variables
Variables inside a function are local to that function and cannot be accessed outside it (local scope). Variables defined outside a function have global scope.
x = 10 # Global variable
def func():
x = 5 # Local variable
print("Inside function:", x)
func() # Output: Inside function: 5
print("Outside function:", x) # Output: Outside function: 10
To modify a global variable inside a function, use the global
keyword:
x = 10
def modify_global():
global x
x = 20
modify_global()
print(x) # Output: 20
5. Lambda Functions
Lambda functions are anonymous, one-liner functions defined using the lambda
keyword.
# Syntax: lambda arguments: expression
square = lambda x: x ** 2
print(square(5)) # Output: 25
# Multiple arguments
add = lambda a, b: a + b
print(add(3, 7)) # Output: 10
6. Higher-Order Functions
Python supports functions that take other functions as arguments or return them.
- Passing a function as an argument:
def apply_function(func, value): return func(value) double = lambda x: x * 2 print(apply_function(double, 5)) # Output: 10
- Returning a function:
def multiplier(factor): return lambda x: x * factor double = multiplier(2) print(double(4)) # Output: 8
7. Built-in Functions
Python includes many built-in functions for common tasks. Examples include:
len()
: Returns the length of an object.max()
,min()
: Find the maximum or minimum value.sorted()
: Sorts an iterable.map()
,filter()
,reduce()
: Apply functions to iterables.
# Example: Using map to apply a function to a list
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
8. Example: Combining Concepts
def greet_users(names):
"""Greets a list of users."""
for name in names:
print(f"Hello, {name}!")
user_list = ["Alice", "Bob", "Charlie"]
greet_users(user_list)
By mastering functions, you can build modular, reusable, and efficient Python programs!
One response
Really appreciate, it improved my coccepts