Introduction
Functions allow you to write reusable, modular code that makes programs more efficient and maintainable. This step will guide you through defining functions, function arguments, return values, lambda functions, and modules.
1. Defining and Calling Functions
Functions allow you to encapsulate code logic into reusable blocks.
Basic Function Definition
def greet():
print("Hello, Python!")
greet()
Function with Parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Function with Return Value
def add(a, b):
return a + b
result = add(5, 3)
print(result)
2. Function Arguments and Default Values
Python functions support positional arguments, keyword arguments, and default values.
Default Arguments
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
Keyword Arguments
def user_info(name, age):
print(f"Name: {name}, Age: {age}")
user_info(age=30, name="Bob")
Variable-Length Arguments (*args
and **kwargs
)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # Output: 10
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_details(name="Alice", age=25, city="New York")
3. Lambda (Anonymous) Functions
Lambda functions are small anonymous functions defined using the lambda
keyword.
Lambda Function Example
square = lambda x: x ** 2
print(square(5)) # Output: 25
Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
4. Working with Modules
Modules allow you to organize Python code into separate files and reuse functions across different scripts.
Creating and Importing a Module
- Create a file
math_operations.py
:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
- Import and use the module:
import math_operations
print(math_operations.add(5, 3))
Using Specific Functions from a Module
from math_operations import add
print(add(10, 5))
Using Built-in Modules (Example: math
)
import math
print(math.sqrt(16)) # Output: 4.0
Exercises
- Write a function that takes two numbers and returns their product.
- Create a function with default parameters and test calling it with and without arguments.
- Write a lambda function that returns the maximum of two numbers.
- Create a Python module with at least two functions and import it into another script.
- Use the
math
module to calculate the square root and factorial of a number.
Conclusion
You have now learned how to define and use functions, work with arguments, create lambda functions, and use modules to structure your code efficiently. The next step is to work with file handling and exception handling in Python.