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
Here's your Telegram post for Day 17!

---

Hey Pythonistas! 👋 Day 17 is here, and we're diving into a cornerstone of modern web development and data exchange: **JSON** (JavaScript Object Notation). 🌐 It's the lightweight, human-readable format used extensively for APIs, configuration files, and more. Python makes handling JSON incredibly easy with its built-in `json` module. You'll learn how to convert Python dictionaries/lists to JSON strings and files, and vice versa. Let's unlock the power of data interchange! 🚀

```python
import json
import os

# --- Part 1: Python objects to JSON strings (serialization) ---
# A Python dictionary
user_data = {
"name": "Alex",
"age": 28,
"is_active": True,
"skills": ["Python", "API", "Databases"],
"preferences": {"theme": "dark", "notifications": True},
"last_login": None
}

# Convert Python dict to JSON string (dumps = "dump string")
# 'indent=4' makes the JSON output pretty-printed for readability
json_string = json.dumps(user_data, indent=4)
print("--- Python Dictionary to JSON String ---")
print(json_string)

# --- Part 2: JSON strings to Python objects (deserialization) ---
# A JSON string
json_text = '''
{
"product": "Wireless Mouse",
"price": 25.99,
"available": true,
"ratings": 4.5
}
'''

# Convert JSON string to Python dictionary (loads = "load string")
product_dict = json.loads(json_text)
print("n--- JSON String to Python Dictionary ---")
print(f"Product: {product_dict['product']}")
print(f"Price: ${product_dict['price']}")
print(f"Is available: {product_dict['available']}")
print(f"Type of product_dict: {type(product_dict)}")

# --- Part 3: Python objects to JSON files (serialization to file) ---
file_name = "my_data.json"
config_data = {
"app_name": "MyCoolApp",
"version": "1.0.0",
"settings": {
"log_level": "INFO",
"max_connections": 100
}
}

# Write Python dict to a JSON file (dump = "dump to file")
with open(file_name, 'w') as f:
json.dump(config_data, f, indent=4)
print(f"n--- Python Dictionary written to '{file_name}' ---")

# --- Part 4: JSON files to Python objects (deserialization from file) ---
# Read JSON from a file into a Python dictionary (load = "load from file")
if os.path.exists(file_name):
with open(file_name, 'r') as f:
loaded_config = json.load(f)
print(f"--- JSON from '{file_name}' loaded into Python Dictionary ---")
print(f"App Name: {loaded_config['app_name']}")
print(f"Log Level: {loaded_config['settings']['log_level']}")

# Clean up the created file
os.remove(file_name)
print(f"'{file_name}' removed.")
else:
print(f"Error: '{file_name}' not found for loading.")
```

Output example:
```
--- Python Dictionary to JSON String ---
{
"name": "Alex",
"age": 28,
"is_active": true,
"skills": [
"Python",
"API",
"Databases"
],
"preferences": {
"theme": "dark",
"notifications": true
},
"last_login": null
}

--- JSON String to Python Dictionary ---
Product: Wireless Mouse
Price: $25.99
Is available: True
Type of product_dict: <class 'dict'>

--- Python Dictionary written to 'my_data.json' ---

--- JSON from 'my_data.json' loaded into Python Dictionary ---
App Name: MyCoolApp
Log Level: INFO
'my_data.json' removed.
```

### Your Challenge! 🧠💡
Create a list of Python dictionaries, where each dictionary represents an employee with keys like `id`, `name`, `department`, and `salary`. Convert this list into a JSON string and print it. Then, write this same data to a file named `employees.json`. Finally, load `employees.json` back into a Python list and print the names of all employees who work in the "Marketing" department. Don't forget to clean up the file!

---

### Quiz Question ❓
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? 🤯

---