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 24: Lambda Functions and List Comprehensions \- Code & Output
Here's your Telegram post for Day 25 on Unit Testing!

---

🌟 **Day 25: Unit Testing - Build Robust Python Code!** 🌟

Today, we're diving into a crucial practice for every developer: **Unit Testing!** πŸš€ Learning to write tests ensures your code works as expected, catches bugs early, and makes future changes safer. Python's built-in `unittest` module makes it straightforward to test individual units (functions or methods) of your code. Let's see how! βœ…

```python
# --- math_operations.py (or just part of your script for this example) ---

def add(a, b):
"""Adds two numbers and returns the sum."""
return a + b

def multiply(a, b):
"""Multiplies two numbers and returns the product."""
return a * b

# --- test_math_operations.py (or continue in the same file) ---
import unittest

# Assuming add and multiply functions are accessible (e.g., defined above or imported)

class TestMathOperations(unittest.TestCase):
def test_add_positive_numbers(self):
"""Test adding two positive numbers."""
self.assertEqual(add(2, 3), 5)

def test_add_negative_numbers(self):
"""Test adding two negative numbers."""
self.assertEqual(add(-1, -1), -2)

def test_add_zero(self):
"""Test adding a number to zero."""
self.assertEqual(add(0, 5), 5)

def test_multiply_positive_numbers(self):
"""Test multiplying two positive numbers."""
self.assertEqual(multiply(2, 4), 8)

def test_multiply_by_zero(self):
"""Test multiplying by zero."""
self.assertEqual(multiply(5, 0), 0)

def test_multiply_negative_numbers(self):
"""Test multiplying positive and negative numbers."""
self.assertEqual(multiply(3, -2), -6)

# This block allows you to run the tests directly from the script
if __name__ == '__main__':
unittest.main()
```

**Output example:**
```
......
----------------------------------------------------------------------
Ran 6 tests in 0.001s

OK
```
(You'd run this by saving the code as `test_math_operations.py` and then executing `python test_math_operations.py` in your terminal.)

### Small Challenge:
Can you add a new function `divide(a, b)` to our `math_operations.py` and write at least two test cases for it in `TestMathOperations`? Don't forget to consider edge cases like division by zero! πŸ’‘

---
Day 25: Unit Testing \- Code & Output
Which assertion method from `unittest.TestCase` would you use to check if two values are not equal?
Anonymous Quiz
0%
assertEqual()
0%
assertTrue()
0%
assertNotEqual()
0%
assertIsNone()
πŸŽ‰ **Day 26: Basic Web Scraping (Beautiful Soup)** πŸŽ‰

Ready to dive into the exciting world of extracting data from websites? πŸ•ΈοΈ Today, we're taking our first steps into web scraping with the powerful Beautiful Soup library! πŸ₯£ Beautiful Soup makes parsing HTML and XML documents a breeze, allowing us to navigate, search, and modify the parse tree.

We'll learn how to fetch specific elements like titles, paragraphs, and links from a simple webpage. Get ready to turn unstructured web content into usable data! πŸ’»βœ¨

```python
import requests
from bs4 import BeautifulSoup

# In a real scenario, you'd fetch HTML from a URL:
# response = requests.get("https://example.com")
# html_doc = response.text

# For this example, we'll use a static HTML string
html_doc = """
<html>
<head>
<title>My Awesome Learning Page</title>
</head>
<body>
<h1>Welcome to Web Scraping!</h1>
<p class="intro">This is the first paragraph about our Python journey.</p>
<p>Day 26 is all about Beautiful Soup.</p>
<a href="https://beautiful-soup-4.readthedocs.io/en/latest/" id="bs_docs">Beautiful Soup Documentation</a>
</body>
</html>
"""

# Parse the HTML content using Beautiful Soup
soup = BeautifulSoup(html_doc, 'html.parser')

print("--- Extracted Data ---")

# 1. Get the title of the page
page_title = soup.title
print(f"Page Title: {page_title.string}")

# 2. Find the first h1 tag
h1_tag = soup.find('h1')
print(f"H1 Content: {h1_tag.text}")

# 3. Find a specific paragraph by its class
intro_paragraph = soup.find('p', class_='intro')
print(f"Intro Paragraph: {intro_paragraph.text}")

# 4. Find a link by its ID and get its href attribute
docs_link = soup.find(id='bs_docs')
print(f"Docs Link URL: {docs_link.get('href')}")
```

Output example:
```
--- Extracted Data ---
Page Title: My Awesome Learning Page
H1 Content: Welcome to Web Scraping!
Intro Paragraph: This is the first paragraph about our Python journey.
Docs Link URL: https://beautiful-soup-4.readthedocs.io/en/latest/
```

### Small Challenge:
Can you modify the code to find and print the text of *all* `<p>` tags on the page? Hint: Look for a method that finds multiple elements!

---
Day 26: Basic Web Scraping \(Beautiful Soup\) \- Code & Output
Which of the following Beautiful Soup methods is used to find the *first* occurrence of a specific tag in an HTML document?
Anonymous Quiz
0%
find_all()
0%
select()
100%
find()
0%
get_text()
Here's your Telegram post for Day 27!

---

πŸŽ‰ Day 27: Introduction to Flask/Django! πŸŽ‰

Hello, future web developers! πŸš€ Today, we're taking our first exciting step into the world of Python web development. We're introducing you to Flask and Django, two incredibly powerful frameworks that let you build dynamic websites and web applications using Python. We'll start with a simple "Hello, World!" example using Flask to show you just how accessible web development can be! Get ready to bring your Python skills to life on the web! πŸŒπŸ’»

```python
# Day 27: First steps with Flask!
# Make sure you have Flask installed:
# pip install Flask

from flask import Flask

# Create a Flask application instance
app = Flask(__name__)

# Define a route for the home page ('/')
@app.route('/')
def hello_world():
"""Returns a simple greeting for the home page."""
return 'Hello from Flask, Day 27 Learners! πŸ‘‹ Welcome to Web Dev!'

# Define another route for an 'about' page
@app.route('/about')
def about_page():
"""Returns information about this app."""
return 'This is a basic Flask introduction app. Pretty cool, right?'

# Run the Flask app if this script is executed directly
if __name__ == '__main__':
# debug=True enables debug mode, which provides helpful error messages
# and automatically reloads the server on code changes.
app.run(debug=True)
```

**Output example:**
When you run the Python script (`python your_app_name.py`), you'll see output similar to this in your terminal:
```
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: XXX-XXX-XXX
```
Now, open your web browser and navigate to `http://127.0.0.1:5000/`. You should see:
`Hello from Flask, Day 27 Learners! πŸ‘‹ Welcome to Web Dev!`

If you go to `http://127.0.0.1:5000/about`, you'll see:
`This is a basic Flask introduction app. Pretty cool, right?`

**Small Challenge:**
1. Modify the `hello_world` function to display *your name* instead of "Day 27 Learners!".
2. Add a new route, `/greet/<name>`, that takes a name as part of the URL and returns a personalized greeting. For example, visiting `http://127.0.0.1:5000/greet/Alice` should show "Hello, Alice! Nice to meet you in Flask!". (Hint: Look up how to use variable rules in Flask routes!)

---
Day 27: Introduction to Flask/Django \- Code & Output
πŸš€ Day 28: Diving into Asynchronous Programming with `asyncio`! ⏳

Today, we're unlocking the power of non-blocking I/O with Python's `asyncio` library! 🧠 Ever wanted your program to do multiple things without waiting for each one to finish? That's what `asyncio` is for! It allows concurrent execution of operations, making your applications more responsive and efficient, especially for I/O-bound tasks like network requests or reading files. Get ready to `async` and `await` your way to faster Python code! πŸ”₯

```python
import asyncio
import time

# An asynchronous function simulating an I/O operation
async def fetch_data(item_id, delay):
print(f"[{time.strftime('%H:%M:%S')}] Fetching data for item {item_id}...")
await asyncio.sleep(delay) # Simulate a non-blocking delay
print(f"[{time.strftime('%H:%M:%S')}] Data for item {item_id} fetched after {delay}s.")
return f"Item {item_id} data"

# The main asynchronous function to orchestrate tasks
async def main():
print(f"[{time.strftime('%H:%M:%S')}] Starting main async operations.")

# Run multiple async tasks concurrently
# asyncio.gather waits for all specified awaitables to complete.
results = await asyncio.gather(
fetch_data("A", 3),
fetch_data("B", 1),
fetch_data("C", 2)
)

print(f"[{time.strftime('%H:%M:%S')}] All data fetching complete!")
print(f"Final results: {results}")

if __name__ == "__main__":
# asyncio.run() executes the top-level entry point and manages the event loop.
asyncio.run(main())
```

Output example:
```
[HH:MM:SS] Starting main async operations.
[HH:MM:SS] Fetching data for item A...
[HH:MM:SS] Fetching data for item B...
[HH:MM:SS] Fetching data for item C...
[HH:MM:SS] Data for item B fetched after 1s.
[HH:MM:SS] Data for item C fetched after 2s.
[HH:MM:SS] Data for item A fetched after 3s.
[HH:MM:SS] All data fetching complete!
Final results: ['Item A data', 'Item B data', 'Item C data']
```
*(Note: `HH:MM:SS` will reflect the actual execution time)*

### Small challenge:
Modify the `main` function to create a new task using `asyncio.create_task()` for fetching data for "D" with a 4-second delay, instead of adding it to `asyncio.gather`. How would you await its completion along with the `gather` call? Hint: You might need another `await`! πŸ’‘

---
Day 28: Asynchronous Programming \(asyncio\) \- Code & Output
Here's your Telegram post for Day 29!

---

πŸ₯³ Day 29: Database Dive! πŸ₯³

Ready to make your Python apps store and retrieve data persistently? Today, we're diving into basic database interaction using **SQLite**! πŸ—„οΈ It's a lightweight, serverless database perfect for learning and many small-to-medium projects.

We'll learn how to:
βœ… Connect to a database
βœ… Create a table
βœ… Insert new records
βœ… Query existing data

Let's make our data stick! πŸ’Ύ

```python
import sqlite3

def main():
# 1. Connect to a SQLite database (or create it if it doesn't exist)
# Using 'with' statement ensures the connection is properly closed even if errors occur.
with sqlite3.connect('my_python_data.db') as conn:
cursor = conn.cursor()

# 2. Create a table
# IF NOT EXISTS prevents an error if the table already exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
print("Table 'users' ensured to exist.")

# 3. Insert data
# Note: Running this multiple times will add duplicate users.
# For a real application, you'd add logic to check for existing data first.
new_users = [
('Eve', 28),
('Frank', 42),
('Grace', 31)
]
print(f"Attempting to insert {len(new_users)} new users...")
try:
# The '?' are placeholders for safe parameter substitution
cursor.executemany("INSERT INTO users (name, age) VALUES (?, ?)", new_users)
# 4. Commit changes (save them permanently to the database file)
conn.commit()
print("New users inserted and changes committed.")
except sqlite3.IntegrityError as e:
print(f"Error inserting users: {e}. Perhaps a unique constraint was violated.")
conn.rollback() # Rollback changes if an error occurred

# 5. Query data
print("nAll users currently in the database:")
# Select specific columns for clarity and order by ID
cursor.execute("SELECT id, name, age FROM users ORDER BY id ASC")
for row in cursor.fetchall(): # fetchall() retrieves all results
print(row)

print("nDatabase operations completed. You can find 'my_python_data.db' in your directory!")

if __name__ == "__main__":
main()
```

Output example:
```
Table 'users' ensured to exist.
Attempting to insert 3 new users...
New users inserted and changes committed.

All users currently in the database:
(1, 'Eve', 28)
(2, 'Frank', 42)
(3, 'Grace', 31)

Database operations completed. You can find 'my_python_data.db' in your directory!
```
*(Note: If you run the script multiple times, the 'id' numbers will continue to increment, and you'll see duplicate 'Eve', 'Frank', 'Grace' entries unless you add logic to prevent it.)*

πŸ’‘ **Challenge:**
Modify the script to:
1. Add another new user with a unique name and age.
2. Update the age of 'Eve' to 30.
3. Delete the user 'Frank' from the database.
Remember to `conn.commit()` your changes after `INSERT`, `UPDATE`, and `DELETE`! ✨

---
Day 29: Basic Database Interaction \(SQLite\) \- Code & Output
In Python's `sqlite3` module, what is the primary purpose of calling `conn.commit()` after executing SQL commands like `INSERT` or `UPDATE`?
Anonymous Quiz
0%
To save the changes permanently to the database file.
0%
To close the database connection safely.
0%
To rollback any changes made since the last commit.
0%
To fetch all results from a `SELECT` query.
πŸ₯³ **Day 30: Final Project Idea and Review!** πŸš€

We've reached a significant milestone, Pythonistas! πŸŽ‰ Today isn't about learning complex new syntax, but about *applying* everything you've absorbed over the past month. We'll explore ideas for your final project and crucial steps for reviewing your progress. It's time to consolidate your knowledge, think creatively, and prepare to build something truly yours! Let's get ready to turn concepts into code! ✨

```python
import random

def get_project_idea_and_review_prompt():
"""
Suggests a project type and provides prompts for self-review.
"""
project_types = [
"a command-line utility (e.g., a file organizer)",
"a simple web application (using Flask/Django basics for a 'Hello World' app)",
"a data analysis script (e.g., parsing a CSV file)",
"a text-based game (e.g., 'Guess the Number')",
"an automation script (e.g., renaming multiple files)"
]

suggested_type = random.choice(project_types)

print(f"🌟 Your Final Project Idea Suggestion: Build {suggested_type}!")
print("n--- Project Planning & Review Prompts ---")
print("1. What's the *core problem* or *functionality* your project aims to provide?")
print("2. List 3-5 Python concepts/modules from this series you'll definitely use.")
print("3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?")
print("4. What's one *minimum viable feature* you'll implement first?")
print("5. What potential challenges do you foresee and how might you tackle them?")
print("nGood luck building your masterpiece! You've got this! πŸ’ͺ")

if __name__ == "__main__":
get_project_idea_and_review_prompt()
```

Output example:
```
🌟 Your Final Project Idea Suggestion: Build a data analysis script (e.g., parsing a CSV file)!

--- Project Planning & Review Prompts ---
1. What's the *core problem* or *functionality* your project aims to provide?
2. List 3-5 Python concepts/modules from this series you'll definitely use.
3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?
4. What's one *minimum viable feature* you'll implement first?
5. What potential challenges do you foresee and how might you tackle them?

Good luck building your masterpiece! You've got this! πŸ’ͺ
```

**Small Challenge:**
Your Challenge: Modify the `get_project_idea_and_review_prompt` function to *also* suggest 2-3 specific Python modules (e.g., `os`, `csv`, `requests`, `datetime`) that would be particularly useful for the randomly chosen project type. How would you map modules to project types? πŸ€”

---
Day 30: Final Project Idea and Review \- Code & Output
πŸš€ Day 31: Ready to elevate your Python architecture? Today, we're diving into **Architecting with Algebraic Data Types (ADTs)** and leveraging Python's powerful `match/case` statement for robust state machines! 🎯 Discover how to model complex domains with unparalleled clarity and reduce bugs by making invalid states impossible. This paradigm shift will transform how you handle control flow and state management, leading to cleaner, more maintainable code. Let's build truly robust systems! ✨

```python
from dataclasses import dataclass
from typing import Union

# Simulate Algebraic Data Types (ADTs) using dataclasses
# Each class represents a distinct state (a "variant" of the sum type)

@dataclass(frozen=True)
class Red:
duration: int = 30 # seconds

@dataclass(frozen=True)
class Yellow:
duration: int = 5

@dataclass(frozen=True)
class Green:
duration: int = 45

# Our "ADT" for TrafficLightState is effectively Red | Yellow | Green
TrafficLightState = Union[Red, Yellow, Green] # Using Union for type hinting pre-Python 3.10, or | for 3.10+

def transition_light(current_state: TrafficLightState, action: str) -> TrafficLightState:
"""
Transitions the traffic light state based on the current state and action.
Uses Python's match/case for elegant state machine logic.
"""
if action == "NEXT":
match current_state:
case Red(duration):
print(f"🚦 Currently Red for {duration}s. Transitioning to Yellow.")
return Yellow()
case Yellow(duration):
print(f"🚦 Currently Yellow for {duration}s. Transitioning to Green.")
return Green()
case Green(duration):
print(f"🚦 Currently Green for {duration}s. Transitioning to Red.")
return Red()
case _: # Catch-all for unhandled states (should ideally be unreachable)
raise ValueError(f"Unknown traffic light state encountered: {current_state}")
else:
raise ValueError(f"Unknown action: {action}")

# Initial state
current_light = Red()
print(f"Initial State: {current_light}")

# Simulate transitions
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")

current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")

current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")

current_light = transition_light(current_light, "NEXT") # Go back to Yellow
print(f"New State: {current_light}")

```

Output example:
```
Initial State: Red(duration=30)
🚦 Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)

🚦 Currently Yellow for 5s. Transitioning to Green.
New State: Green(duration=45)

🚦 Currently Green for 45s. Transitioning to Red.
New State: Red(duration=30)

🚦 Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)
```

πŸ’‘ **Your Challenge:** Extend our `TrafficLightState`! Add a `FlashingYellow` state that can be reached from `Yellow` (perhaps on a specific `action` like "FLASH") and then transitions back to `Yellow` or `Red` depending on your logic. How would you update the `transition_light` function using `match/case`?

---
πŸš€ Day 32 Alert! Get ready to dive deep into Python's core! Ever wondered how Python *really* executes your code? This session, "The Bytecode Whisperer," unpacks the Abstract Syntax Tree (AST) – the hidden blueprint of your programs. We'll learn to dissect it, manipulate it, and even rewrite it on the fly. Unleash truly dynamic behavior and explore extreme optimization techniques that go beyond conventional Python. Prepare to wield immense power! ✨

```python
import ast

# Original Python code as a string
original_code = """
def greet():
message = "Hello, Pythonista!"
print(message)

greet()
"""

# 1. Parse the original code into an AST
tree = ast.parse(original_code)

# 2. Define a custom AST transformer
class GreetTransformer(ast.NodeTransformer):
def visit_Constant(self, node):
# Change string literals within the AST
if isinstance(node.value, str) and node.value == "Hello, Pythonista!":
return ast.Constant(value="Bonjour, cher dΓ©veloppeur!")
return node

def visit_FunctionDef(self, node):
# Inject a print statement at the beginning of the function body
if node.name == "greet":
new_print_stmt = ast.Expr(
value=ast.Call(
func=ast.Name(id='print', ctx=ast.Load()),
args=[ast.Constant(value="--- AST Magic Ahead! ---")],
keywords=[]
)
)
node.body.insert(0, new_print_stmt) # Insert at the beginning
return self.generic_visit(node) # Ensure other nodes are visited

# 3. Transform the AST
transformer = GreetTransformer()
new_tree = transformer.visit(tree)

# 4. Fix missing line numbers and other metadata in the new tree
ast.fix_missing_locations(new_tree)

# 5. Compile the modified AST
compiled_code = compile(new_tree, '<string>', 'exec')

# 6. Execute the modified code
print("--- Executing AST-Transformed Code ---")
exec(compiled_code)
```

Output example:
```
--- Executing AST-Transformed Code ---
--- AST Magic Ahead! ---
Bonjour, cher dΓ©veloppeur!
```

Challenge accepted! πŸš€ Can you modify the `GreetTransformer` to also inject another `print` statement at the *end* of the `greet` function's body, saying '--- AST Magic Complete! ---'?
Which of the following modules is primarily used for parsing Python source code into an Abstract Syntax Tree (AST)?
Anonymous Quiz
0%
dis
0%
ast
0%
inspect
0%
codecs