1. Module
- Explanation: A module is a file containing Python code, which can include functions, classes, and variables. Modules can be imported and used in other Python scripts.
import math # Imports the math module, which provides mathematical functions.
2. Exception Handling
- Explanation: Exception handling is a way to handle errors gracefully during program execution. The '
try'
, 'except'
, and 'finally'
blocks are used for this.
try: result = 10 / 0 except ZeroDivisionError: print("You can't divide by zero!")
3. Lambda Function
- Explanation: A lambda function is a small, anonymous function defined using the
lambda
keyword. It can take any number of arguments but has only one expression.
square = lambda x: x * 2 # A lambda function to calculate the square of a number.
4. List Comprehension
- Explanation: List comprehension is a concise way to create lists. It can replace loops and '
map'
/'filter'
functions.
squares = [x**2 for x in range(10)] # Creates a list of squares from 0 to 9.
5. Decorator
- Explanation: A decorator is a function that takes another function and extends its behavior without explicitly modifying it. It is commonly used in scenarios like logging or authorization.
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!")
No comments:
Post a Comment