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 20: Working with Dates and Times \- Code & Output
Which `strftime` format code would you use to display the full weekday name (e.g., 'Monday', 'Tuesday')?
Anonymous Quiz
0%
%a
0%
%w
0%
%A
0%
%W
Here's your Telegram post for Day 21 on Python Decorators!

---

**Day 21: Decorators ✨ Unlocking Python Magic!**

Ready to add powerful functionality to your functions without changing their core code? Today, we're diving into Python Decorators! πŸͺ„ These amazing tools act as wrappers, allowing you to modify or enhance functionsβ€”think logging, authentication, or performance timingβ€”with a simple `@` syntax. It's a clean and elegant way to extend behavior. Let's see them in action! πŸ‘‡

```python
def my_logger_decorator(func):
"""A simple decorator that logs function calls."""
def wrapper(*args, **kwargs):
print(f"πŸš€ Calling function: {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"βœ… Function {func.__name__} finished. Result: {result}")
return result
return wrapper

@my_logger_decorator
def add(a, b):
"""Adds two numbers."""
return a + b

@my_logger_decorator
def say_hello(name, greeting="Hello"):
"""Greets a person."""
print(f"{greeting}, {name}!")
return f"{greeting}, {name}!"

# Using our decorated functions
print("--- Calling add(5, 3) ---")
sum_result = add(5, 3)
print(f"Add function returned: {sum_result}n")

print("--- Calling say_hello('Alice', greeting='Hi') ---")
hello_message = say_hello('Alice', greeting='Hi')
print(f"Say_hello function returned: {hello_message}")
```

Output example:
```
--- Calling add(5, 3) ---
πŸš€ Calling function: add with args: (5, 3), kwargs: {}
βœ… Function add finished. Result: 8
Add function returned: 8

--- Calling say_hello('Alice', greeting='Hi') ---
πŸš€ Calling function: say_hello with args: ('Alice',), kwargs: {'greeting': 'Hi'}
Hi, Alice!
βœ… Function say_hello finished. Result: Hi, Alice!
Say_hello function returned: Hi, Alice!
```

**Small challenge:**
Can you create a decorator called `@timer` that measures and prints the execution time of the decorated function? ⏱️ Share your solution in the comments! πŸ‘‡

---
Day 21: Decorators \- Code & Output
πŸš€ Day 22: Unlocking Python's Power with Generators & Iterators! 🐍

Today, we dive into the magic of memory-efficient data processing. Learn how **generators** allow you to create sequences on-the-fly without storing the entire sequence in memory – perfect for huge datasets! We'll explore the `yield` keyword and how **iterators** work behind the scenes to produce values one by one. Get ready to write more performant and scalable Python code! ✨

```python
def countdown_generator(n):
"""A simple generator that counts down from n."""
print(f"Starting countdown from {n}...")
while n >= 0:
yield n # Pause execution and yield a value
n -= 1
print("Countdown finished!")

# --- Using a for loop to iterate over the generator ---
print("--- Iterating with a for loop (n=3) ---")
for num in countdown_generator(3):
print(f"Current count: {num}")

print("n--- Manually iterating with next() (n=2) ---")
# --- Manually iterating using next() ---
gen = countdown_generator(2)
try:
print(f"First value: {next(gen)}")
print(f"Second value: {next(gen)}")
print(f"Third value: {next(gen)}")
# Trying to get another value after exhaustion raises StopIteration
print(f"Fourth value: {next(gen)}")
except StopIteration:
print("Caught StopIteration: Generator is exhausted.")

```

Output example:
```
--- Iterating with a for loop (n=3) ---
Starting countdown from 3...
Current count: 3
Current count: 2
Current count: 1
Current count: 0
Countdown finished!

--- Manually iterating with next() (n=2) ---
Starting countdown from 2...
First value: 2
Second value: 1
Third value: 0
Caught StopIteration: Generator is exhausted.
Countdown finished!
```

πŸ’‘ **Your Challenge:** Modify the `countdown_generator` to create a `fibonacci_generator(limit)` that yields Fibonacci numbers up to a specified `limit`! Share your solution! πŸ‘‡

---
πŸ‘‹ 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! πŸ‘‡

---