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 and quiz question!

---

Hey Python learners! πŸ‘‹

Ever wondered how to manage dates and times in your Python programs? ⏰ Today, on Day 20 of our series, we dive deep into the incredibly powerful `datetime` module! From getting the current time to calculating durations and formatting dates, this module is your go-to for all temporal tasks. Let's make your programs time-aware! πŸ—“οΈ

```python
from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(f"Current Date & Time: {now}")

# Create a specific date and time
specific_date = datetime(2023, 1, 15, 10, 30, 0)
print(f"Specific Date: {specific_date}")

# Format dates into a string (strftime)
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date (YYYY-MM-DD HH:MM:SS): {formatted_date}")

# Format with more detail
user_friendly_date = now.strftime("%A, %B %d, %Y at %I:%M %p")
print(f"User-Friendly Date: {user_friendly_date}")

# Parse a string into a datetime object (strptime)
date_string = "2024-07-20 14:00:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date from string: {parsed_date}")

# Calculate time differences (timedelta)
time_difference = now - specific_date
print(f"Time difference since specific date: {time_difference}")

# Add or subtract time
future_date = now + timedelta(days=7, hours=3)
print(f"Date 7 days and 3 hours from now: {future_date}")

# Accessing components
print(f"Current Year: {now.year}, Month: {now.month}, Day: {now.day}")
```

Output example:
```
Current Date & Time: 2024-07-20 10:35:45.123456
Specific Date: 2023-01-15 10:30:00
Formatted Date (YYYY-MM-DD HH:MM:SS): 2024-07-20 10:35:45
User-Friendly Date: Saturday, July 20, 2024 at 10:35 AM
Parsed Date from string: 2024-07-20 14:00:00
Time difference since specific date: 552 days, 0:05:45.123456
Date 7 days and 3 hours from now: 2024-07-27 13:35:45.123456
Current Year: 2024, Month: 7, Day: 20
```

### 🧠 Small Challenge:
Can you write a short Python snippet to calculate how many days are left until Christmas 2024? (Hint: You'll need `datetime` for Christmas, `datetime.now()` for today, and `timedelta` to find the difference!)

Happy coding, and see you tomorrow! πŸš€

---

### Quiz Question:
Day 20: Working with Dates and Times \- Code & Output
What will be the output of `datetime(2024, 7, 20, 15, 30).strftime('%d-%m-%Y %I:%M %p')`?
Anonymous Quiz
100%
20-07-2024 03:30 PM
0%
20-07-2024 15:30 PM
0%
07-20-2024 03:30 PM
0%
20-07-2024 03:30 AM
Here's your Telegram post and quiz question for Day 21 on Decorators!

---

πŸ₯³ Day 21 already! Today, we're diving into one of Python's most elegant and powerful features: *Decorators*! ✨

Think of them as wrappers that allow you to modify or enhance the behavior of a function or a method without permanently changing its code. They're super handy for adding extra functionality like logging, timing, authentication, or input validation. Let's unravel their magic! 🎩

```python
import time
import functools

# Our first decorator: A simple timer
def timer_decorator(func):
@functools.wraps(func) # Important for preserving original func metadata
def wrapper(*args, **kwargs):
start_time = time.perf_counter() # Record start time
result = func(*args, **kwargs) # Execute the original function
end_time = time.perf_counter() # Record end time
print(f"βŒ›οΈ Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds.")
return result
return wrapper

# Applying the decorator using the @ syntax
@timer_decorator
def calculate_sum(n):
"""Calculates the sum of numbers up to n."""
total = 0
for i in range(n + 1):
total += i
time.sleep(0.01) # Simulate some work
return total

@timer_decorator
def greet(name):
"""Greets a person."""
time.sleep(0.005) # Simulate some work
return f"Hello, {name}!"

# --- Using the decorated functions ---
print(f"Sum: {calculate_sum(100000)}")
print(greet("Pythonista"))
```

Output example:
```
βŒ›οΈ Function 'calculate_sum' executed in 0.0112 seconds.
Sum: 5000050000
βŒ›οΈ Function 'greet' executed in 0.0053 seconds.
Hello, Pythonista!
```

Challenging you: πŸ’ͺ Can you create a *`logger_decorator`* that prints the arguments a function received before executing it? For example, `Calling 'my_func' with args=(1, 2), kwargs={'name': 'Alice'}`.

---
Day 21: Decorators \- Code & Output
Here's your Telegram post for Day 22!

---

πŸš€ Day 22 of our Python journey! Today, we unlock the power of **Generators** and **Iterators**! πŸ’‘ These aren't just fancy terms; they're essential tools for writing memory-efficient and scalable code, especially when dealing with large datasets. Forget loading everything into memory at once – generators let you produce values on the fly. Let's dive into how `yield` makes magic happen! ✨

```python
# A simple generator function
def count_up_to(n):
i = 0
print(f"Generator initialized (counting up to {n}).")
while i < n:
print(f"Yielding {i}...")
yield i # Pauses execution and returns i. Resumes from here on next() call.
i += 1
print("Generator finished.")

# Using the generator
print("--- Using next() explicitly ---")
my_counter = count_up_to(3) # This just creates the generator object, doesn't run yet

print(f"First value: {next(my_counter)}")
print(f"Second value: {next(my_counter)}")

try:
print(f"Third value: {next(my_counter)}")
print(f"Attempting fourth value: {next(my_counter)}") # This will raise StopIteration
except StopIteration:
print("Caught StopIteration! Generator is exhausted.")

print("n--- Using a for loop (the cleaner way) ---")
# Generators are iterables, so they work great with for loops
for num in count_up_to(5):
print(f"Received in loop: {num}")

# Practical example: Infinite sequence (but we'll limit it for demo)
def even_numbers():
n = 0
while True: # This would be infinite, but we'll break it
yield n
n += 2

print("n--- First 5 even numbers ---")
evens = even_numbers()
for _ in range(5):
print(next(evens))
```

Output example:
```
--- Using next() explicitly ---
Generator initialized (counting up to 3).
Yielding 0...
First value: 0
Yielding 1...
Second value: 1
Yielding 2...
Third value: 2
Generator finished.
Caught StopIteration! Generator is exhausted.

--- Using a for loop (the cleaner way) ---
Generator initialized (counting up to 5).
Yielding 0...
Received in loop: 0
Yielding 1...
Received in loop: 1
Yielding 2...
Received in loop: 2
Yielding 3...
Received in loop: 3
Yielding 4...
Received in loop: 4
Generator finished.

--- First 5 even numbers ---
0
2
4
6
8
```

πŸ’‘ **Challenge:** Create a generator function called `reverse_string_generator(s)` that takes a string `s` and yields its characters one by one in reverse order. Then, use a `for` loop to print them out! Share your elegant solution! πŸ‘‡

---
Day 22: Generators and Iterators \- Code & Output
What is the primary keyword used to define a generator function in Python?
Anonymous Quiz
0%
return
0%
yield
0%
generate
100%
iterate
Here's your Telegram post for Day 23!

---

**Day 23: Context Managers (with statement) ✨**

Hello Python learners! πŸš€ Today, we're diving into one of Python's most elegant features for resource management: **Context Managers** using the `with` statement. Ever worry about closing files or releasing resources properly? Context managers automate this cleanup, making your code safer and cleaner. πŸ”’ They ensure resources are acquired at the start and *always* released at the end, even if errors occur. No more forgotten `file.close()` calls!

```python
import os

# Example 1: Writing to a file safely
print("--- Writing to a file ---")
file_name = "daily_log.txt"
with open(file_name, "w") as log_file:
log_file.write("Python learning day 23!n")
log_file.write("Context managers are awesome.n")
print(f"Content written to '{file_name}'.")

# Example 2: Reading from a file safely
print("n--- Reading from the file ---")
with open(file_name, "r") as log_file:
content = log_file.read()
print("File content:")
print(content)

print(f"File '{file_name}' operations complete. The file is automatically closed.")

# Clean up the created file
try:
os.remove(file_name)
print(f"nCleaned up: '{file_name}' removed.")
except OSError as e:
print(f"Error removing file {file_name}: {e}")
```

Output example:
```
--- Writing to a file ---
Content written to 'daily_log.txt'.

--- Reading from the file ---
File content:
Python learning day 23!
Context managers are awesome.

File 'daily_log.txt' operations complete. The file is automatically closed.

Cleaned up: 'daily_log.txt' removed.
```

**Small Challenge: πŸ€”**
Can you modify the reading example to *iterate through each line* of the `daily_log.txt` file instead of reading all content at once? Print each line along with its line number (starting from 1).

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

---

**Python Learning Series: Day 24**

πŸš€ Day 24 is here! Today, we're unlocking two incredibly powerful Python features that will make your code more concise and efficient: **Lambda Functions** and **List Comprehensions**! πŸ’‘

Lambda functions are small, anonymous functions perfect for quick, single-expression tasks. List comprehensions, on the other hand, provide a clean and compact way to create lists. Get ready to write some super elegant Python! πŸ”₯ Let's dive in!

```python
# Lambda Functions: Small, anonymous functions
# Syntax: lambda arguments: expression

# Example 1: Simple lambda to double a number
double = lambda x: x * 2
print(f"Doubled 5: {double(5)}")

# Example 2: Using lambda with map() to apply a function to all items
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(f"Original numbers: {numbers}")
print(f"Doubled numbers (using map + lambda): {doubled_numbers}")

# List Comprehensions: Concise way to create lists

# Example 3: Creating a list of squares
squares = [x**2 for x in range(1, 6)]
print(f"Squares from 1 to 5: {squares}")

# Example 4: Creating a list of even numbers with a condition
even_numbers = [x for x in range(10) if x % 2 == 0]
print(f"Even numbers from 0 to 9: {even_numbers}")

# Example 5: Combining transformation and filtering in a list comprehension
transformed_evens = [x * 3 for x in range(10) if x % 2 == 0]
print(f"Evens * 3 from 0 to 9: {transformed_evens}")
```

Output example:
```
Doubled 5: 10
Original numbers: [1, 2, 3, 4, 5]
Doubled numbers (using map + lambda): [2, 4, 6, 8, 10]
Squares from 1 to 5: [1, 4, 9, 16, 25]
Even numbers from 0 to 9: [0, 2, 4, 6, 8]
Evens * 3 from 0 to 9: [0, 6, 12, 18, 24]
```

πŸ’‘ **Your Challenge!**
Create a list containing the squares of all odd numbers between 1 and 20 (inclusive) using a single list comprehension. Share your solution in the comments! πŸ‘‡

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

Ever wonder how to make your Python code super reliable? Today, we dive into Unit Testing! This crucial practice helps you catch bugs early, ensure individual components of your code work as expected, and makes refactoring a breeze. We'll be using Python's built-in `unittest` module to write robust tests. Let's make our code bulletproof and build confidence in every line! πŸ’ͺ

```python
import unittest

# The function we want to test
def add(a, b):
"""Adds two numbers and returns the sum."""
return a + b

# Our test class, inheriting from unittest.TestCase
class TestAddFunction(unittest.TestCase):

def test_add_positive_numbers(self):
"""Test with two positive numbers."""
self.assertEqual(add(2, 3), 5)

def test_add_negative_numbers(self):
"""Test with two negative numbers."""
self.assertEqual(add(-1, -5), -6)

def test_add_mixed_numbers(self):
"""Test with a positive and a negative number."""
self.assertEqual(add(10, -3), 7)

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

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

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

OK
```

πŸ’‘ Your Challenge:
Add a new test method to `TestAddFunction` that checks the addition of floating-point numbers (e.g., `add(2.5, 3.5)`). What result do you expect? Share your code snippet or just the expected outcome! πŸ€”

---
Day 25: Unit Testing \- Code & Output
Which `unittest.TestCase` method is commonly used to verify if two values are equal in Python unit tests?
Anonymous Quiz
0%
self.assertTrue()
100%
self.assertFalse()
0%
self.assertEqual()
0%
self.assertIsNone()
Here's your Telegram post for Day 26!

---

✨ Day 26: Basic Web Scraping (Beautiful Soup) ✨

Ready to extract data from websites? πŸ•ΈοΈ Today, we dive into the exciting world of web scraping with **Beautiful Soup**! This powerful Python library helps you parse HTML and XML documents, making it easy to navigate and search the parse tree. Learn how to fetch content and extract exactly what you need. Let's turn unstructured web data into structured information! πŸš€

```python
from bs4 import BeautifulSoup
import requests # Generally used to fetch web pages, but we'll use a string for demo.

# A simple HTML string for demonstration purposes
html_doc = """
<html><head><title>The Scraped Page</title></head>
<body>
<p class="title"><b>My First Heading</b></p>
<p class="story">
Hello there! Here's some content.
<a href="http://example.com/link1" class="link">Link 1</a>
<a href="http://example.com/link2" class="link">Link 2</a>
</p>
<p class="footer">End of page.</p>
</body></html>
"""

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

# Print the title of the page
print("Page Title:", soup.title.string)

# Find the first paragraph with class "story"
story_paragraph = soup.find('p', class_='story')
print("Story Paragraph Text:", story_paragraph.get_text(strip=True))

# Find all anchor (<a>) tags
all_links = soup.find_all('a')
print("nAll Links:")
for link in all_links:
print(f"Text: {link.string}, Href: {link.get('href')}")
```

Output example:
```
Page Title: The Scraped Page
Story Paragraph Text: Hello there! Here's some content.Link 1Link 2

All Links:
Text: Link 1, Href: http://example.com/link1
Text: Link 2, Href: http://example.com/link2
```

**Small Challenge:**
Can you modify the code to find and print only the text inside the `<b>` tag within the `p` with class "title"? 🧐

---
Here's your Telegram post for Day 27!

---

πŸš€ **Day 27: Introduction to Flask/Django!** 🌐

Today, we're taking our first steps into the exciting world of Python web development! We'll explore Flask and Django, two incredibly powerful frameworks that let you build everything from simple APIs to complex, full-featured websites. Flask is known for its lightweight, "micro-framework" approach, giving you more control. Django, on the other hand, is a "batteries-included" framework, offering a robust set of tools out-of-the-box. Let's kick things off with a super basic Flask app! ✨

```python
from flask import Flask

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

# Define a route for the home page ('/')
@app.route('/')
def home():
return 'Hello from our first Flask app! 🐍'

# This block ensures the server runs only when the script is executed directly
if __name__ == '__main__':
# Make sure to install Flask first: pip install Flask
# Run the app in debug mode (helpful for development)
app.run(debug=True)
```

**Output example:**
When you run the script (`python your_script_name.py`), you'll see output similar to this in your terminal:

```
* Serving Flask app 'your_script_name'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
```

Now, open your web browser and navigate to `http://127.0.0.1:5000`. You should see the message: `Hello from our first Flask app! 🐍`

**Small challenge:**
Your Challenge:
Can you modify the code to add another route, `/greet/<name>`, that takes a name as a parameter (e.g., `http://127.0.0.1:5000/greet/Alice`) and returns "Hello, [name]! Welcome to Flask!"? Hint: You'll need `from flask import request` and `@app.route('/greet/<name>')`! Good luck! πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

---