<div style="position: relative; padding-bottom: 64.90384615384616%; height: 0;"><iframe src="https://www.loom.com/embed/7a1d783441e14beca2cc3edde841e307?sid=f29f4d84-76b4-4446-9e85-d79198dca191" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe></div>
#### Introduction
Python modules are collections of functions and variables that extend the functionality of Python. They help you avoid writing code from scratch and can be easily integrated into your own programs. This lesson focuses on some of the most common built-in modules in Python that are versatile and applicable across many different types of programs.
#### 1. `random` Module
- **Purpose**: To generate pseudo-random numbers for various probabilistic processes.
- **Common Uses**:
- Randomizing data
- Simulating events
- Developing games
- **Key Functions**:
- `random.randint(a, b)`: Returns a random integer N such that a <= N <= b.
- `random.choice(sequence)`: Returns a randomly selected element from a non-empty sequence.
- `random.shuffle(sequence)`: Shuffles the sequence in place.
#### 2. `time` Module
- **Purpose**: To interact with time-related tasks.
- **Common Uses**:
- Adding delays in programs
- Measuring the execution time of code
- **Key Functions**:
- `time.sleep(seconds)`: Suspends execution for the given number of seconds.
- `time.time()`: Returns the current time in seconds since the Epoch.
#### 3. `datetime` Module
- **Purpose**: To handle date and time information more complex than what `time` provides.
- **Common Uses**:
- Logging events
- Analyzing time-series data
- **Key Functions**:
- `datetime.datetime.now()`: Returns the current local date and time.
- `datetime.timedelta(days=0, seconds=0, ...)`: Represents a duration, the difference between two dates or times.
#### 4. `functools` Module
- **Purpose**: To facilitate higher-order functions and operations on callable objects.
- **Common Uses**:
- Functional programming
- Decorators
- **Key Functions**:
- `functools.lru_cache(maxsize=128, typed=False)`: Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls.
- `functools.partial(func, /, *args, **keywords)`: Returns a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.
#### 5. `itertools` Module
- **Purpose**: To provide a set of tools for creating iterators for efficient looping.
- **Common Uses**:
- Complex data manipulation
- Efficient looping
- **Key Functions**:
- `itertools.cycle(iterable)`: Returns elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.
- `itertools.permutations(iterable, r=None)`: Returns successive r length permutations of elements in the iterable.
#### Cross-Module Example
Let's use a few of these modules together to create a simple program that simulates a dice game:
```python
import random
import itertools
import time
def roll_dice():
return random.randint(1, 6)
def play_round():
player_score = sum(itertools.islice((roll_dice() for _ in itertools.count()), 5))
print(f"Player rolled {player_score}")
time.sleep(2) # Delay the game for dramatic effect
return player_score
def game():
print("Starting the dice game...")
scores = [play_round() for _ in range(3)]
print(f"Total score: {sum(scores)}")
game()
```
#### Cheat Sheet
- `random`: Use for randomness-related tasks.
- `time`: Use for time measurement and delays.
- `datetime`: Use when you need to manipulate dates and times.
- `functools`: Utilize for functional programming techniques.
- `itertools`: Ideal for creating complex iterators.
#### Exercise
Create a simple program that:
1. Uses the `datetime` module to log the start and end time of the program.
2. Utilizes `itertools` to generate and print 3 unique combinations of two numbers between 1 and 10.
3. Uses `random` to randomly select one of these combinations.