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
πŸ‘‹ Hey Python learners! Day 23 is here, and we're diving into a Python superpower: *Context Managers* using the `with` statement! πŸš€

Ever forget to close a file or release a lock? The `with` statement is your elegant solution for ensuring resources are properly managed and cleaned up automatically, even if errors occur. It makes your code safer, cleaner, and more Pythonic! Get ready to simplify resource handling. Let's explore! πŸ‘‡

```python
# Day 23: Context Managers (with statement)

# --- Example 1: File Handling with 'with' ---
print("--- File Handling Demo ---")
try:
# 'with' ensures the file is closed automatically,
# even if an error occurs during writing/reading.
with open("my_document.txt", "w") as file_writer:
file_writer.write("Hello from Day 23!n")
file_writer.write("Context Managers are awesome!n")
print("Successfully wrote to my_document.txt")

with open("my_document.txt", "r") as file_reader:
content = file_reader.read()
print(f"Content read:n{content}")
print("File automatically closed after 'with' block.")

# --- Example 2: Demonstrating cleanup on error ---
print("n--- Error Handling Demo ---")
with open("error_test.log", "w") as log_file:
log_file.write("Starting critical operation...n")
# Simulate an error
raise ValueError("Critical operation failed!")
log_file.write("This line will not be reached.n") # Unreachable
except ValueError as e:
print(f"Caught an expected error: {e}")
# Even though an error occurred, log_file was closed
# before the exception was propagated.
print("The 'error_test.log' file was still automatically closed!")
except Exception as e:
print(f"An unexpected error occurred: {e}")

print("n--- Demo Complete ---")
```

Output example:
```
--- File Handling Demo ---
Successfully wrote to my_document.txt
Content read:
Hello from Day 23!
Context Managers are awesome!

File automatically closed after 'with' block.

--- Error Handling Demo ---
Caught an expected error: Critical operation failed!
The 'error_test.log' file was still automatically closed!

--- Demo Complete ---
```

πŸ’‘ **Your Challenge:** What happens if you try to access `file_reader` (from the example's `with open(...) as file_reader:`) *after* its `with` block has finished? For instance, try adding `print(file_reader.closed)` or `file_reader.read()` right after the first `with` block. Try it and see if you can catch the error (or the boolean value)! Share your findings! πŸ‘‡

---
Day 23: Context Managers \(with statement\) \- Code & Output
Here's your Telegram post for Day 24!

---

**Python Learning Series - Day 24: Lambda Functions and List Comprehensions**

Day 24 is here! πŸš€ Today, we're diving into two incredibly powerful and Pythonic features: *Lambda Functions* and *List Comprehensions*! ✨ Learn how to write concise, single-expression anonymous functions and create lists with elegant, readable syntax. Master these, and your Python code will become much cleaner and more efficient! 🐍 Let's go!

```python
# Day 24: Lambda Functions and List Comprehensions

# 1. Lambda Functions (anonymous, single-expression functions)
# A lambda function to square a number
square_lambda = lambda x: x * x
print(f"Lambda square(5): {square_lambda(5)}")

# Using lambda with map() to apply a function to all items in an iterable
numbers = [1, 2, 3, 4, 5]
lambda_squared_numbers = list(map(lambda x: x * x, numbers))
print(f"Lambda with map: {lambda_squared_numbers}")

# 2. List Comprehensions (a concise way to create lists)
# Create a list of squares using list comprehension
list_comprehension_squares = [x * x for x in numbers]
print(f"List comprehension squares: {list_comprehension_squares}")

# List comprehension with a condition (filter even numbers and square them)
even_squared_list = [x * x for x in numbers if x % 2 == 0]
print(f"Even numbers squared (LC): {even_squared_list}")

# Another example: filtering strings
words = ["apple", "banana", "kiwi", "grapefruit", "orange"]
long_words_uppercase = [word.upper() for word in words if len(word) > 5]
print(f"Long words uppercase (LC): {long_words_uppercase}")
```

**Output example:**
```
Lambda square(5): 25
Lambda with map: [1, 4, 9, 16, 25]
List comprehension squares: [1, 4, 9, 16, 25]
Even numbers squared (LC): [4, 16]
Long words uppercase (LC): ['BANANA', 'GRAPEFRUIT', 'ORANGE']
```

πŸ’‘ **Your Challenge!**
Given a list of dictionaries representing products:
`products = [{'name': 'Laptop', 'price': 1200}, {'name': 'Mouse', 'price': 25}, {'name': 'Keyboard', 'price': 75}, {'name': 'Monitor', 'price': 300}]`

Use a *list comprehension* to create a new list containing only the `name` of products that have a `price` greater than 100. Share your solution in the comments! πŸ‘‡

---
Day 24: Lambda Functions and List Comprehensions \- Code & Output
πŸš€ Day 25: Unit Testing! πŸš€

Time to make your code robust and reliable! Today, we dive into the world of Unit Testing, an essential practice for any developer. πŸ›πŸš« Python's built-in `unittest` module makes it super easy to write tests that catch bugs early, ensure your functions work as expected, and give you confidence in your code. Let's see how! πŸ‘‡

```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_add_positive_numbers(self):
"""Test with positive integers."""
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(10, 20), 30)

def test_add_negative_numbers(self):
"""Test with negative integers."""
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(-5, 2), -3) # Mixed signs

def test_add_zero(self):
"""Test with zero."""
self.assertEqual(add(0, 5), 5)
self.assertEqual(add(5, 0), 5)
self.assertEqual(add(0, 0), 0)

def test_add_float_numbers(self):
"""Test with floating-point numbers."""
self.assertAlmostEqual(add(0.1, 0.2), 0.3)
self.assertEqual(add(1.5, 2.5), 4.0)

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

Output example:
```
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK
```

πŸ’‘ **Your Challenge:**
What if you wanted your `add` function to concatenate strings instead of adding numbers? Modify the `add` function to handle both (perhaps with a type check), then add new test methods to `TestAddFunction` to ensure it works correctly for string concatenation! βž•πŸ”—

---
Day 25: Unit Testing \- Code & Output
Here's your Telegram post for Day 26: Basic Web Scraping with Beautiful Soup!

---

πŸ“š Day 26: Basic Web Scraping (Beautiful Soup) πŸ•ΈοΈ

Today, we're diving into the exciting world of web scraping! ✨ Learn how to extract information from websites using Python's fantastic Beautiful Soup library. Beautiful Soup makes parsing HTML and XML documents a breeze, allowing you to navigate, search, and modify the parse tree. It's an essential tool for data collection, research, and automating tasks. Let's start with a simple example!

```python
from bs4 import BeautifulSoup

# A simple HTML string for demonstration purposes
html_doc = """
<html>
<head>
<title>Beautiful Soup Demo Page</title>
</head>
<body>
<h1>Welcome to Web Scraping!</h1>
<p class="intro">This is an introduction to Beautiful Soup.</p>
<a href="https://www.python.org">Python Website</a>
<div id="footer">
<p>Copyright 2023</p>
</div>
</body>
</html>
"""

# Create a BeautifulSoup object
soup = BeautifulSoup(html_doc, 'html.parser')

# Extract the page title
title_tag = soup.title
print(f"Page Title: {title_tag.string}")

# Extract the text from the h1 tag
h1_tag = soup.h1
print(f"H1 Content: {h1_tag.string}")

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

Output example:
```
Page Title: Beautiful Soup Demo Page
H1 Content: Welcome to Web Scraping!
Intro Paragraph: This is an introduction to Beautiful Soup.
```

πŸš€ **Challenge:**
Can you modify the code to extract the `href` attribute from the `<a>` tag and the text content from the `div` with `id="footer"`? Share your solutions!

---
Day 26: Basic Web Scraping \(Beautiful Soup\) \- Code & Output
Here's your Telegram post and quiz:

---

πŸš€ Day 27: Web Wonders! 🌐 Ready to build your first web app? Today, we're diving into the exciting world of Python web frameworks with an introduction to Flask and Django! These powerful tools let you create dynamic websites, APIs, and more. We'll start with a super simple Flask example to get your feet wet and see how easy it is to serve content directly from Python. Let's make some magic happen! ✨

```python
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 'Hello, World!' message when the home page is accessed."""
return "Hello from Flask, Pythonista! 🌍"

# Run the application if this script is executed directly
if __name__ == '__main__':
# debug=True enables the debugger and auto-reloader, great for development
app.run(debug=True)
```

Output example:
(When you run the script, open your browser and navigate to `http://127.0.0.1:5000/`)

*Console output when running `python your_script_name.py`:*
```
* 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
```

*What you'll see in your browser:*
```
Hello from Flask, Pythonista! 🌍
```

### Small challenge:
✨ Try changing the message returned by `hello_world()` to something else, like `return "Welcome to my first web page with Flask!"`. Can you also add another route, say `/about`, that returns information about yourself or the learning series? Hint: You'll need another `@app.route('/about')` decorator and a new function. Good luck! πŸ’‘

---
Here's your Telegram post and quiz question!

---

πŸŽ‰ Day 28: Diving into Asynchronous Programming with `asyncio`! πŸš€

Today, we're tackling one of Python's most powerful features for efficient, non-blocking I/O operations and concurrency: `asyncio`! πŸ’‘ Ever wondered how to make your programs run multiple tasks seemingly at once without getting stuck? `asyncio` is your answer! We'll explore `async` and `await` to write concurrent code that scales. Let's make our Python faster and more responsive! ⏱️

```python
import asyncio
import time

async def fetch_data(delay, item_name):
"""Simulates an asynchronous I/O operation like fetching data from a network."""
print(f"⏳ {item_name}: Starting data fetch (will take {delay}s)...")
await asyncio.sleep(delay) # Non-blocking pause
print(f"βœ… {item_name}: Data fetched!")
return f"Data for {item_name}"

async def main():
start_time = time.monotonic()
print("πŸš€ Main program started!")

# Run multiple coroutines concurrently
results = await asyncio.gather(
fetch_data(3, "User Profile"),
fetch_data(1, "Product List"),
fetch_data(2, "Order History")
)

end_time = time.monotonic()
print("--- All fetches completed! ---")
for res in results:
print(f"Retrieved: {res}")
print(f"Total time taken: {end_time - start_time:.2f} seconds.")

if __name__ == "__main__":
asyncio.run(main())
```

Output example:
```
πŸš€ Main program started!
⏳ User Profile: Starting data fetch (will take 3s)...
⏳ Product List: Starting data fetch (will take 1s)...
⏳ Order History: Starting data fetch (will take 2s)...
βœ… Product List: Data fetched!
βœ… Order History: Data fetched!
βœ… User Profile: Data fetched!
--- All fetches completed! ---
Retrieved: Data for User Profile
Retrieved: Data for Product List
Retrieved: Data for Order History
Total time taken: 3.00 seconds.
```

Challenge: πŸ€”
Modify the `main` function to use `asyncio.create_task()` for each `fetch_data` call instead of `asyncio.gather()`. How would you then collect their results? Share your solution! ✍️

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

---

**Python Learning Series - Day 29: Basic Database Interaction (SQLite)**

Day 29 is here! πŸš€ Ever wondered how your Python apps can store and retrieve data persistently? Today, we dive into the world of databases with SQLite! πŸ’Ύ We'll learn the basics of connecting, creating tables, inserting data, and fetching results using Python's built-in `sqlite3` module. Get ready to give your scripts a memory! πŸ§ πŸ’»

```python
import sqlite3

# 1. Connect to an SQLite database (or create one if it doesn't exist)
# Using 'my_app_data.db' will create a file. ':memory:' would create an in-memory DB.
conn = sqlite3.connect('my_app_data.db')
cursor = conn.cursor()

# 2. Create a table
# IF NOT EXISTS prevents error if table already exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')

# 3. Insert some data
# Using '?' as placeholders for parameters for safety and convenience
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Bob", 24))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Charlie", 35))

# 4. Commit changes (save them to the database file)
conn.commit()

# 5. Fetch data
print("All users:")
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall() # Fetch all results
for row in rows:
print(row)

# 6. Close the connection
conn.close()
print("nDatabase operations completed. 'my_app_data.db' created/updated.")
```

Output example:
```
All users:
(1, 'Alice', 30)
(2, 'Bob', 24)
(3, 'Charlie', 35)

Database operations completed. 'my_app_data.db' created/updated.
```

πŸ’‘ **Challenge:**
Modify the code to:
1. Insert one more user into the `users` table.
2. Select and print only users whose age is greater than 25.

Share your solution or just let us know you tried! πŸ‘‡

---
Day 29: Basic Database Interaction \(SQLite\) \- Code & Output
Which method of a `cursor` object is used to execute SQL commands in Python's `sqlite3` module?
Anonymous Quiz
0%
execute()
0%
run_sql()
0%
query()
0%
perform()
πŸ₯³ *Congratulations on reaching Day 30 of our Python series!* 🐍

Today is all about gearing up for your Final Project! πŸŽ‰ It's time to consolidate everything you've learned into something truly your own. We'll explore how to brainstorm ideas and review key concepts we've covered. Don't be overwhelmed – think of it as a creative challenge! Let's get those project ideas flowing! πŸ’‘

---

Here's a little helper to get your brainstorming started:

```python
import random

def generate_project_idea():
categories = [
"Web Application",
"Command-Line Tool",
"Data Analysis Script",
"Game",
"Automation Script",
"Desktop Application",
"API Integration"
]
themes = [
"personal finance tracker",
"to-do list manager",
"simple calculator",
"weather app",
"file organizer",
"quiz game",
"recipe book",
"contact manager"
]
technologies = [
"using Flask",
"with SQLite database",
"fetching data from an API",
"using object-oriented programming",
"with a GUI library like Tkinter",
"using Pandas for data manipulation"
]

idea_category = random.choice(categories)
idea_theme = random.choice(themes)
idea_tech = random.choice(technologies)

return f"πŸ’‘ Your project idea: A {idea_category} that is a {idea_theme} {idea_tech}."

if __name__ == "__main__":
print(generate_project_idea())
```

Output example:
```
πŸ’‘ Your project idea: A Web Application that is a recipe book using Flask.
```

---

**Your Challenge:**
1. What's one project idea you've been thinking about building with Python? Share it!
2. Expand the `generate_project_idea` function to include more categories, themes, or even suggest specific Python libraries to use. πŸš€

---
Day 30: Final Project Idea and Review \- Code & Output
πŸš€ Day 31: Ready to peer into Python's soul? πŸ•΅οΈβ€β™‚οΈ Today, we're diving deep into the **Abstract Syntax Tree (AST)**! Forget just writing code; we'll learn how Python *sees* your code at its structural core. Understanding ASTs empowers you to build incredible tools: custom linters, code generators, refactoring scripts, and even new language features! ✨ This is pure metaprogramming magic. Let's crack open the parser! πŸ› οΈ

```python
import ast

# Sample Python code to analyze
code_snippet = """
def greet(name):
print(f"Hello, {name}!")

class MyClass:
def __init__(self, value):
self.value = value

def display(self):
return f"Value: {self.value}"

def calculate_sum(a, b):
# This is a comment
return a + b
"""

class NodeCounter(ast.NodeVisitor):
"""
A simple AST visitor to count different types of nodes
and find function names.
"""
def __init__(self):
self.node_counts = {}
self.function_names = []

def visit(self, node):
# Count all node types
node_type = type(node).__name__
self.node_counts[node_type] = self.node_counts.get(node_type, 0) + 1

# Specific action for FunctionDef
if isinstance(node, ast.FunctionDef):
self.function_names.append(node.name)

self.generic_visit(node) # Continue visiting children

# Parse the code into an AST
tree = ast.parse(code_snippet)

# Create an instance of our visitor and traverse the tree
counter = NodeCounter()
counter.visit(tree)

print("πŸ“Š AST Analysis Results:")
print("-----------------------")
print("Detected Function Names:")
for func_name in counter.function_names:
print(f"- {func_name}")

print("nNode Type Counts:")
for node_type, count in sorted(counter.node_counts.items()):
print(f"- {node_type}: {count}")
```

Output example:
```
πŸ“Š AST Analysis Results:
-----------------------
Detected Function Names:
- greet
- __init__
- display
- calculate_sum

Node Type Counts:
- Arg: 4
- Arguments: 4
- Assign: 1
- Attribute: 1
- BinOp: 1
- Call: 1
- ClassDef: 1
- Constant: 3
- Expr: 1
- FString: 1
- FormattedValue: 1
- FunctionDef: 4
- Load: 8
- Module: 1
- Name: 12
- Return: 2
- Store: 1
- With: 0
```

### Small Challenge 🧠
Can you modify the `NodeCounter` class to also find and list all `ClassDef` names present in the `code_snippet`? Hint: You'll need to look for `ast.ClassDef` nodes!

---