Which `re` module function is typically used to find *all* non-overlapping matches of a pattern in a string and return them as a list of strings?
Anonymous Quiz
0%
re.findall()
0%
0%
re.match()
0%
re.sub()
๐ Day 19: Mastering Python Virtual Environments! ๐
Ever faced "dependency hell" where one project needs a different package version than another? Say goodbye to conflicts! Today, we're diving into virtual environments โ your secret weapon for isolating project dependencies. Keep your projects clean, organized, and conflict-free. Let's set up our isolated workspaces! โจ๐ฆ
Here's how you use them:
```python
# 1. Create a virtual environment (replace 'my_project_env' with your desired name)
python -m venv my_project_env
# 2. Activate the virtual environment
# On macOS/Linux:
source my_project_env/bin/activate
# On Windows (Command Prompt):
my_project_envScriptsactivate
# On Windows (PowerShell):
my_project_envScriptsActivate.ps1
# 3. Install a package inside the activated environment
pip install requests
# 4. See installed packages (it will only show packages in this venv)
pip list
# 5. Deactivate the virtual environment
deactivate
```
Output example:
```
(base) user@host:~$ python -m venv my_project_env
(base) user@host:~$ source my_project_env/bin/activate
(my_project_env) user@host:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 62.6/62.6 kB 390.6 kB/s eta 0:00:00
Collecting idna<4,>=2.5
Downloading idna-3.6-py3-none-any.whl (61 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 61.8/61.8 kB 403.6 kB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
Downloading charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (119 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 119.8/119.8 kB 506.7 kB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
Downloading urllib3-2.1.0-py3-none-any.whl (104 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 104.5/104.5 kB 558.1 kB/s eta 0:00:00
Collecting certifi>=2017.4.17
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 162.5/162.5 kB 588.6 kB/s eta 0:00:00
Installing collected packages: idna, charset-normalizer, urllib3, certifi, requests
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(my_project_env) user@host:~$ pip list
Package Version
---------------- ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
setuptools 68.2.2
urllib3 2.1.0
(my_project_env) user@host:~$ deactivate
(base) user@host:~$
```
๐ก **Your Challenge:**
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library using `pip`.
4. Confirm `numpy` is listed using `pip list`.
5. Deactivate your environment.
Share your success in the comments! ๐
Ever faced "dependency hell" where one project needs a different package version than another? Say goodbye to conflicts! Today, we're diving into virtual environments โ your secret weapon for isolating project dependencies. Keep your projects clean, organized, and conflict-free. Let's set up our isolated workspaces! โจ๐ฆ
Here's how you use them:
```python
# 1. Create a virtual environment (replace 'my_project_env' with your desired name)
python -m venv my_project_env
# 2. Activate the virtual environment
# On macOS/Linux:
source my_project_env/bin/activate
# On Windows (Command Prompt):
my_project_envScriptsactivate
# On Windows (PowerShell):
my_project_envScriptsActivate.ps1
# 3. Install a package inside the activated environment
pip install requests
# 4. See installed packages (it will only show packages in this venv)
pip list
# 5. Deactivate the virtual environment
deactivate
```
Output example:
```
(base) user@host:~$ python -m venv my_project_env
(base) user@host:~$ source my_project_env/bin/activate
(my_project_env) user@host:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 62.6/62.6 kB 390.6 kB/s eta 0:00:00
Collecting idna<4,>=2.5
Downloading idna-3.6-py3-none-any.whl (61 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 61.8/61.8 kB 403.6 kB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
Downloading charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (119 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 119.8/119.8 kB 506.7 kB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
Downloading urllib3-2.1.0-py3-none-any.whl (104 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 104.5/104.5 kB 558.1 kB/s eta 0:00:00
Collecting certifi>=2017.4.17
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 162.5/162.5 kB 588.6 kB/s eta 0:00:00
Installing collected packages: idna, charset-normalizer, urllib3, certifi, requests
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(my_project_env) user@host:~$ pip list
Package Version
---------------- ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
setuptools 68.2.2
urllib3 2.1.0
(my_project_env) user@host:~$ deactivate
(base) user@host:~$
```
๐ก **Your Challenge:**
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library using `pip`.
4. Confirm `numpy` is listed using `pip list`.
5. Deactivate your environment.
Share your success in the comments! ๐
What is the primary purpose of using Python virtual environments?
Anonymous Quiz
0%
To speed up the execution of Python scripts.
0%
To create isolated environments for different projects to manage their dependencies independently.
0%
To globally install all Python packages on your system.
0%
To automatically back up your Python code to the cloud.
Here's your Telegram post and quiz question!
---
๐ Day 20: Mastering Dates & Times in Python! ๐ โฐ
Time flies, but you can definitely manage it in your Python programs! Today, we're diving into the powerful `datetime` module to handle dates and times with ease. Learn to fetch the current moment, format it just how you like, and even parse date strings back into objects. Get ready to conquer time! ๐๏ธโจ
```python
import datetime
# Get current date and time
current_dt = datetime.datetime.now()
print(f"Current Date & Time: {current_dt}")
# Format the date and time into a readable string
formatted_dt = current_dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date & Time: {formatted_dt}")
# Format for a different style (e.g., Day, Month Day, Year Hour:Minute AM/PM)
custom_format = current_dt.strftime("%A, %B %d, %Y %I:%M %p")
print(f"Custom Formatted: {custom_format}")
# Parse a string into a datetime object
date_string = "2024-07-20 14:30:00"
parsed_dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date & Time: {parsed_dt}")
```
Output example:
```
Current Date & Time: 2023-10-27 10:30:45.123456
Formatted Date & Time: 2023-10-27 10:30:45
Custom Formatted: Friday, October 27, 2023 10:30 AM
Parsed Date & Time: 2024-07-20 14:30:00
```
Small challenge:
Can you create a `datetime` object for January 1st, 2025, at 00:00:00, and then format it to display as "Wednesday, Jan 1, 2025"? Share your code! ๐
---
---
๐ Day 20: Mastering Dates & Times in Python! ๐ โฐ
Time flies, but you can definitely manage it in your Python programs! Today, we're diving into the powerful `datetime` module to handle dates and times with ease. Learn to fetch the current moment, format it just how you like, and even parse date strings back into objects. Get ready to conquer time! ๐๏ธโจ
```python
import datetime
# Get current date and time
current_dt = datetime.datetime.now()
print(f"Current Date & Time: {current_dt}")
# Format the date and time into a readable string
formatted_dt = current_dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date & Time: {formatted_dt}")
# Format for a different style (e.g., Day, Month Day, Year Hour:Minute AM/PM)
custom_format = current_dt.strftime("%A, %B %d, %Y %I:%M %p")
print(f"Custom Formatted: {custom_format}")
# Parse a string into a datetime object
date_string = "2024-07-20 14:30:00"
parsed_dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date & Time: {parsed_dt}")
```
Output example:
```
Current Date & Time: 2023-10-27 10:30:45.123456
Formatted Date & Time: 2023-10-27 10:30:45
Custom Formatted: Friday, October 27, 2023 10:30 AM
Parsed Date & Time: 2024-07-20 14:30:00
```
Small challenge:
Can you create a `datetime` object for January 1st, 2025, at 00:00:00, and then format it to display as "Wednesday, Jan 1, 2025"? Share your code! ๐
---
Which `strftime` format code would you use to get the full weekday name (e.g., 'Monday') from a datetime object?
Anonymous Quiz
0%
"%w"
0%
"%a"
0%
"%A"
0%
"%W"
Here's your Telegram post for Day 21 on Decorators!
---
**Day 21: Decorators! ๐ฉโจ**
Today we're diving into one of Python's most elegant and powerful features. Decorators allow you to modify or extend the functionality of a function or method without explicitly changing its source code. Think of them as wrappers! They're super useful for logging, authentication, performance measurement, and more. Get ready to elevate your functions! ๐
```python
import time
# Our first decorator: a simple timer!
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"โฑ๏ธ '{func.__name__}' ran in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Applying the decorator using the '@' syntax
@timer
def simulate_task(duration):
"""Simulates a task that takes some time."""
print(f"Executing task for {duration} seconds...")
time.sleep(duration)
print("Task completed!")
return f"Simulated task finished in {duration}s"
@timer
def calculate_sum(a, b):
"""Calculates the sum of two numbers."""
time.sleep(0.05) # A tiny delay
return a + b
print("--- Calling decorated functions ---")
simulate_task(1.5)
simulate_task(0.8)
sum_result = calculate_sum(10, 20)
print(f"Result of calculation: {sum_result}")
```
Output example:
```
--- Calling decorated functions ---
Executing task for 1.5 seconds...
Task completed!
โฑ๏ธ 'simulate_task' ran in 1.5034 seconds.
Executing task for 0.8 seconds...
Task completed!
โฑ๏ธ 'simulate_task' ran in 0.8012 seconds.
โฑ๏ธ 'calculate_sum' ran in 0.0510 seconds.
Result of calculation: 30
```
**Small challenge:**
Can you modify the `timer` decorator to also print the arguments (`args` and `kwargs`) that the decorated function was called with? Hint: Access them inside the `wrapper` function! ๐ง Good luck!
---
---
**Day 21: Decorators! ๐ฉโจ**
Today we're diving into one of Python's most elegant and powerful features. Decorators allow you to modify or extend the functionality of a function or method without explicitly changing its source code. Think of them as wrappers! They're super useful for logging, authentication, performance measurement, and more. Get ready to elevate your functions! ๐
```python
import time
# Our first decorator: a simple timer!
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"โฑ๏ธ '{func.__name__}' ran in {end_time - start_time:.4f} seconds.")
return result
return wrapper
# Applying the decorator using the '@' syntax
@timer
def simulate_task(duration):
"""Simulates a task that takes some time."""
print(f"Executing task for {duration} seconds...")
time.sleep(duration)
print("Task completed!")
return f"Simulated task finished in {duration}s"
@timer
def calculate_sum(a, b):
"""Calculates the sum of two numbers."""
time.sleep(0.05) # A tiny delay
return a + b
print("--- Calling decorated functions ---")
simulate_task(1.5)
simulate_task(0.8)
sum_result = calculate_sum(10, 20)
print(f"Result of calculation: {sum_result}")
```
Output example:
```
--- Calling decorated functions ---
Executing task for 1.5 seconds...
Task completed!
โฑ๏ธ 'simulate_task' ran in 1.5034 seconds.
Executing task for 0.8 seconds...
Task completed!
โฑ๏ธ 'simulate_task' ran in 0.8012 seconds.
โฑ๏ธ 'calculate_sum' ran in 0.0510 seconds.
Result of calculation: 30
```
**Small challenge:**
Can you modify the `timer` decorator to also print the arguments (`args` and `kwargs`) that the decorated function was called with? Hint: Access them inside the `wrapper` function! ๐ง Good luck!
---
๐ Day 22: Unlocking Python's Power with Generators & Iterators! ๐ Ever needed to process huge datasets without hogging all your RAM? Or wanted to create your own iterable objects? Today's your day! We're diving into the magic of **Iterators** and **Generators**. โจ
They allow for *lazy evaluation*, producing items one by one only when needed, making your code super efficient and memory-friendly. No more loading entire massive lists into memory! Get ready to `yield` some amazing results. Let's see them in action! ๐
```python
# --- Custom Iterator Example ---
class MyRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
# An iterator *is* an iterable that returns itself
return self
def __next__(self):
if self.current < self.end:
num = self.current
self.current += 1
return num
else:
# Signal the end of iteration
raise StopIteration
print("--- Custom Iterator Output ---")
for num in MyRange(1, 4):
print(num)
# --- Generator Function Example ---
# Generators are functions that contain one or more 'yield' statements.
# They pause execution and return a value, resuming from where they left off.
def countdown(n):
print("Starting countdown...")
while n > 0:
yield n # Pause, return n, remember state
n -= 1
print("Countdown finished!")
print("n--- Generator Output ---")
gen = countdown(3) # This creates a generator object, doesn't execute yet
print(next(gen)) # Executes until the first yield
print(next(gen)) # Resumes from where it left off
for val in gen: # Continues iteration until StopIteration is raised internally
print(val)
```
Output example:
```
--- Custom Iterator Output ---
1
2
3
--- Generator Output ---
Starting countdown...
3
2
1
Countdown finished!
```
๐ก **Your Challenge:** Modify the `countdown` generator to also yield "Blast Off!" as its very last item, just before "Countdown finished!" is printed. How would you insert that `yield`? Share your elegant solution!
---
They allow for *lazy evaluation*, producing items one by one only when needed, making your code super efficient and memory-friendly. No more loading entire massive lists into memory! Get ready to `yield` some amazing results. Let's see them in action! ๐
```python
# --- Custom Iterator Example ---
class MyRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
# An iterator *is* an iterable that returns itself
return self
def __next__(self):
if self.current < self.end:
num = self.current
self.current += 1
return num
else:
# Signal the end of iteration
raise StopIteration
print("--- Custom Iterator Output ---")
for num in MyRange(1, 4):
print(num)
# --- Generator Function Example ---
# Generators are functions that contain one or more 'yield' statements.
# They pause execution and return a value, resuming from where they left off.
def countdown(n):
print("Starting countdown...")
while n > 0:
yield n # Pause, return n, remember state
n -= 1
print("Countdown finished!")
print("n--- Generator Output ---")
gen = countdown(3) # This creates a generator object, doesn't execute yet
print(next(gen)) # Executes until the first yield
print(next(gen)) # Resumes from where it left off
for val in gen: # Continues iteration until StopIteration is raised internally
print(val)
```
Output example:
```
--- Custom Iterator Output ---
1
2
3
--- Generator Output ---
Starting countdown...
3
2
1
Countdown finished!
```
๐ก **Your Challenge:** Modify the `countdown` generator to also yield "Blast Off!" as its very last item, just before "Countdown finished!" is printed. How would you insert that `yield`? Share your elegant solution!
---
What is a primary benefit of using generator functions in Python?
Anonymous Quiz
0%
They store all generated values in memory for quick access.
0%
They execute all logic upfront and return a complete list.
0%
They produce values on demand, saving memory for large sequences.
0%
They can only be used with integer sequences.
Here's your Telegram post for Day 23 on Context Managers:
---
๐ Day 23 of our Python journey! Today, we dive into the elegant world of *Context Managers* and the powerful `with` statement. ๐ฉ Ever wondered how to automatically manage resources like files or network connections, ensuring they're properly opened and closed, even if errors occur? The `with` statement is your answer! It simplifies resource handling, making your code cleaner and safer. โจ Get ready to make your resource management effortless!
```python
# Day 23: Context Managers (with statement)
print("--- Using with statement for file handling ---")
# The 'with' statement ensures the file is automatically closed
# even if errors occur during its processing.
with open("my_data.txt", "w") as file:
file.write("Hello, Python learners!n")
file.write("Context managers make resource handling easy.n")
print("File 'my_data.txt' written successfully.")
print("n--- Reading the file with 'with' ---")
try:
with open("my_data.txt", "r") as file:
content = file.read()
print("Content of 'my_data.txt':")
print(content)
except FileNotFoundError:
print("Error: my_data.txt not found. Please run the writing part first.")
print("--- File operations completed ---")
# The file 'my_data.txt' is guaranteed to be closed here.
# You don't need to call file.close() explicitly.
```
Output example:
```
--- Using with statement for file handling ---
File 'my_data.txt' written successfully.
--- Reading the file with 'with' ---
Content of 'my_data.txt':
Hello, Python learners!
Context managers make resource handling easy.
--- File operations completed ---
```
๐ค Small Challenge: Can you modify the file writing part to *append* new lines to `my_data.txt` each time the code runs, instead of overwriting its content? (Hint: check file modes!)
---
Here's your quiz question:
---
๐ Day 23 of our Python journey! Today, we dive into the elegant world of *Context Managers* and the powerful `with` statement. ๐ฉ Ever wondered how to automatically manage resources like files or network connections, ensuring they're properly opened and closed, even if errors occur? The `with` statement is your answer! It simplifies resource handling, making your code cleaner and safer. โจ Get ready to make your resource management effortless!
```python
# Day 23: Context Managers (with statement)
print("--- Using with statement for file handling ---")
# The 'with' statement ensures the file is automatically closed
# even if errors occur during its processing.
with open("my_data.txt", "w") as file:
file.write("Hello, Python learners!n")
file.write("Context managers make resource handling easy.n")
print("File 'my_data.txt' written successfully.")
print("n--- Reading the file with 'with' ---")
try:
with open("my_data.txt", "r") as file:
content = file.read()
print("Content of 'my_data.txt':")
print(content)
except FileNotFoundError:
print("Error: my_data.txt not found. Please run the writing part first.")
print("--- File operations completed ---")
# The file 'my_data.txt' is guaranteed to be closed here.
# You don't need to call file.close() explicitly.
```
Output example:
```
--- Using with statement for file handling ---
File 'my_data.txt' written successfully.
--- Reading the file with 'with' ---
Content of 'my_data.txt':
Hello, Python learners!
Context managers make resource handling easy.
--- File operations completed ---
```
๐ค Small Challenge: Can you modify the file writing part to *append* new lines to `my_data.txt` each time the code runs, instead of overwriting its content? (Hint: check file modes!)
---
Here's your quiz question:
๐ Day 24 is here, and we're diving into two of Python's most powerful features for writing concise and efficient code: Lambda Functions and List Comprehensions! ๐ก
Lambda functions let you create small, anonymous functions on the fly, perfect for quick operations. List comprehensions, on the other hand, provide a compact and readable way to create lists based on existing iterables. Master these, and your Python code will shine! โจ Let's explore how they make your code cleaner and more Pythonic.
```python
# Data to work with
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
words = ["apple", "banana", "kiwi", "grape", "avocado"]
# Lambda Function example: Using with filter() to get even numbers
evens_lambda = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers (lambda): {evens_lambda}")
# List Comprehension example: Squaring only the odd numbers
squares_of_odds = [x**2 for x in numbers if x % 2 != 0]
print(f"Squares of odd numbers (list comprehension): {squares_of_odds}")
# List Comprehension example: Filtering words starting with 'a' and converting to uppercase
a_words_uppercase = [word.upper() for word in words if word.startswith('a')]
print(f"Words starting with 'a' (uppercase LC): {a_words_uppercase}")
```
Output example:
```
Even numbers (lambda): [2, 4, 6, 8, 10]
Squares of odd numbers (list comprehension): [1, 9, 25, 49, 81]
Words starting with 'a' (uppercase LC): ['APPLE', 'AVOCADO']
```
Small challenge:
Can you use a list comprehension to create a new list containing the lengths of only those words from `words` that have more than 4 characters? ๐คฏ
---
Lambda functions let you create small, anonymous functions on the fly, perfect for quick operations. List comprehensions, on the other hand, provide a compact and readable way to create lists based on existing iterables. Master these, and your Python code will shine! โจ Let's explore how they make your code cleaner and more Pythonic.
```python
# Data to work with
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
words = ["apple", "banana", "kiwi", "grape", "avocado"]
# Lambda Function example: Using with filter() to get even numbers
evens_lambda = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers (lambda): {evens_lambda}")
# List Comprehension example: Squaring only the odd numbers
squares_of_odds = [x**2 for x in numbers if x % 2 != 0]
print(f"Squares of odd numbers (list comprehension): {squares_of_odds}")
# List Comprehension example: Filtering words starting with 'a' and converting to uppercase
a_words_uppercase = [word.upper() for word in words if word.startswith('a')]
print(f"Words starting with 'a' (uppercase LC): {a_words_uppercase}")
```
Output example:
```
Even numbers (lambda): [2, 4, 6, 8, 10]
Squares of odd numbers (list comprehension): [1, 9, 25, 49, 81]
Words starting with 'a' (uppercase LC): ['APPLE', 'AVOCADO']
```
Small challenge:
Can you use a list comprehension to create a new list containing the lengths of only those words from `words` that have more than 4 characters? ๐คฏ
---
Here's your Telegram post and quiz question!
---
๐ Day 25: Unit Testing! ๐งช
Today, we dive into one of the most crucial aspects of robust software development: Unit Testing in Python! ๐ก๏ธ Learn how to write tests that verify individual components of your code work exactly as expected. We'll use Python's built-in `unittest` module to ensure our functions are reliable and bug-free. Get ready to build more resilient applications! ๐ช
```python
import unittest
# The function we want to test
def add(a, b):
"""Adds two numbers."""
return a + b
# Our test class, inheriting from unittest.TestCase
class TestAddFunction(unittest.TestCase):
def test_positive_numbers(self):
# Test with positive integers
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(10, 20), 30)
def test_negative_numbers(self):
# Test with negative integers
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(-5, -10), -15)
def test_zero_values(self):
# Test with zeros
self.assertEqual(add(0, 0), 0)
def test_positive_and_negative(self):
# Test with mixed signs
self.assertEqual(add(5, -3), 2)
self.assertEqual(add(-7, 2), -5)
# This block allows you to run the tests directly from the script
if __name__ == '__main__':
unittest.main()
```
Output example:
```
......
----------------------------------------------------------------------
Ran 6 tests in 0.000s
OK
```
**Small Challenge:** Try adding another function, `subtract(a, b)`, to our script and write a new `test_subtract` method within `TestAddFunction` (or create a new `TestSubtractFunction` class!) to test it thoroughly. Think about edge cases like `subtract(5, 0)` or `subtract(0, 5)`! ๐ง
---
---
๐ Day 25: Unit Testing! ๐งช
Today, we dive into one of the most crucial aspects of robust software development: Unit Testing in Python! ๐ก๏ธ Learn how to write tests that verify individual components of your code work exactly as expected. We'll use Python's built-in `unittest` module to ensure our functions are reliable and bug-free. Get ready to build more resilient applications! ๐ช
```python
import unittest
# The function we want to test
def add(a, b):
"""Adds two numbers."""
return a + b
# Our test class, inheriting from unittest.TestCase
class TestAddFunction(unittest.TestCase):
def test_positive_numbers(self):
# Test with positive integers
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(10, 20), 30)
def test_negative_numbers(self):
# Test with negative integers
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(-5, -10), -15)
def test_zero_values(self):
# Test with zeros
self.assertEqual(add(0, 0), 0)
def test_positive_and_negative(self):
# Test with mixed signs
self.assertEqual(add(5, -3), 2)
self.assertEqual(add(-7, 2), -5)
# This block allows you to run the tests directly from the script
if __name__ == '__main__':
unittest.main()
```
Output example:
```
......
----------------------------------------------------------------------
Ran 6 tests in 0.000s
OK
```
**Small Challenge:** Try adding another function, `subtract(a, b)`, to our script and write a new `test_subtract` method within `TestAddFunction` (or create a new `TestSubtractFunction` class!) to test it thoroughly. Think about edge cases like `subtract(5, 0)` or `subtract(0, 5)`! ๐ง
---
What is the primary purpose of unit testing in Python?
Anonymous Quiz
0%
To verify small, isolated parts of code (units) function correctly.
0%
To test the overall integration between different modules of an application.
0%
To measure the performance and speed of a Python program.
0%
To deploy Python applications to production servers.