Python basic to advance
43 subscribers
131 photos
98 links
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
Download Telegram
Day 17: JSON Data Handling \- Code & Output
Which of the following Python data types is *NOT* directly equivalent to a JSON data type?
Anonymous Quiz
0%
String
0%
List
0%
Tuple
100%
Dictionary
Here's your Telegram post for Day 18: Regular Expressions!

---

๐Ÿš€ Day 18: Regular Expressions! ๐Ÿคฏ Get ready to master the art of text pattern matching with Python's powerful `re` module. Regular Expressions (RegEx) are essential for searching, extracting, and manipulating text based on complex patterns. Whether it's validating user input or parsing logs, RegEx is your go-to tool. Let's dive into finding patterns today! ๐Ÿ”๐Ÿ“

```python
import re

text = "Hello Python learners! Today is Day 18. We're diving into Regular Expressions. Find all words, numbers, and underscores!"

# Pattern 1: Find all "words" (alphanumeric characters + underscore)
# w matches any word character (a-z, A-Z, 0-9, _)
# + matches one or more occurrences of the preceding character/group
pattern_words = r'w+'
found_words = re.findall(pattern_words, text)

print("Found 'words':", found_words)

# Pattern 2: Find all numbers
# d matches any digit (0-9)
pattern_numbers = r'd+'
found_numbers = re.findall(pattern_numbers, text)

print("Found numbers:", found_numbers)
```

Output example:
```
Found 'words': ['Hello', 'Python', 'learners', 'Today', 'is', 'Day', '18', 'We', 're', 'diving', 'into', 'Regular', 'Expressions', 'Find', 'all', 'words', 'numbers', 'and', 'underscores']
Found numbers: ['18']
```

๐Ÿ’ก **Small Challenge:** Can you modify the code to find all words in the `text` variable that *start* with 'R' or 'r'? (Hint: Look into `^` for start of string/line and character sets `[]`!)

---
Day 18: Regular Expressions \- Code & Output
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%
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! ๐ŸŽ‰
Day 19: Virtual Environments \- Code & Output
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: Working with Dates and Times \- Code & Output
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 \- Code & Output
๐Ÿš€ 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!

---
Day 22: Generators and Iterators \- Code & Output
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: Context Managers \(with statement\) \- Code & Output
๐Ÿš€ 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? ๐Ÿคฏ

---
Day 24: Lambda Functions and List Comprehensions \- Code & Output
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)`! ๐Ÿง 

---