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 18: Regular Expressions \- Code & Output
What does the regular expression pattern `\d+` match?
Anonymous Quiz
0%
Any single digit
0%
Any word character
0%
One or more digits
0%
Zero or more spaces
๐ŸŒŸ Day 19: Mastering Python Virtual Environments! ๐ŸŒŸ

Ever faced "dependency hell" where different projects need conflicting package versions? ๐Ÿคฏ Virtual environments are your superpower! They create isolated spaces for each project, ensuring clean dependencies and avoiding conflicts. No more global package clutter! Let's learn to manage our Python projects like a pro! โœจ๐Ÿ๐Ÿ“

```python
# --- Common commands for managing virtual environments ---

# 1. Create a virtual environment named 'myproject_env' in your current directory:
# (Run this in your terminal/command prompt)
python -m venv myproject_env

# 2. Activate the virtual environment:
# On macOS/Linux:
source myproject_env/bin/activate
# On Windows (Command Prompt):
myproject_envScriptsactivate
# On Windows (PowerShell):
myproject_envScriptsActivate.ps1

# 3. Install a package (e.g., 'requests') within the active environment:
# (The terminal prompt will usually show the active venv name, e.g., (myproject_env))
pip install requests

# 4. List installed packages in the active environment:
pip freeze

# 5. Deactivate the virtual environment:
deactivate
```

Output example:
```
# After creating and activating 'myproject_env'
(myproject_env) user@machine:~/my_project_folder$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
Collecting charset-normalizer<4,>=2 (from requests)
Downloading charset_normalizer-3.3.2-py3-none-any.whl (38 kB)
...
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0

(myproject_env) user@machine:~/my_project_folder$ pip freeze
certifi==2023.11.17
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.1.0
```

Small challenge:
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library within this environment.
4. Verify `numpy` is installed using `pip freeze`.
5. Deactivate the environment.

---
Day 19: Virtual Environments \- Code & Output
๐Ÿ—“๏ธ Day 20: Time flies when you're learning Python! Today, we're diving into the fascinating world of dates and times with Python's built-in `datetime` module. ๐Ÿ•ฐ๏ธ Managing timestamps, calculating durations, and formatting dates can seem tricky, but Python makes it incredibly powerful and straightforward. Let's master how to handle dates, times, and everything in between! Ready to track moments? Let's go! โœจ

Here's how you can get started:

```python
from datetime import datetime, timedelta, date, time

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

# Create a specific date and time
specific_dt = datetime(2023, 10, 27, 10, 30, 0)
print(f"Specific Date & Time: {specific_dt}")

# Format datetime object into a readable string
formatted_dt = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date: {formatted_dt}")

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

# Working with timedelta (duration calculations)
future_date = now + timedelta(days=7, hours=3)
print(f"Date in 7 days and 3 hours: {future_date}")

# Extracting just the date or just the time
today_date = now.date()
current_time = now.time()
print(f"Just the Date: {today_date}")
print(f"Just the Time: {current_time}")
```

Output example:
```
Current Date & Time: 2024-07-20 10:35:45.123456
Specific Date & Time: 2023-10-27 10:30:00
Formatted Date: 2024-07-20 10:35:45
Parsed Date: 2024-07-20 14:00:00
Date in 7 days and 3 hours: 2024-07-27 13:35:45.123456
Just the Date: 2024-07-20
Just the Time: 10:35:45.123456
```

Challenge Time! ๐Ÿš€
Calculate your exact age in days (or even hours!) using Python's `datetime` and `timedelta` modules. Hint: You'll need your birth date and `datetime.now()`. Good luck!

---
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", "Tuesday") from a `datetime` object?
Anonymous Quiz
0%
%d
0%
%w
0%
%A
100%
%B
โœจ Day 21: Decorators! โœจ

Ready to level up your Python game? Today we dive into one of Python's most elegant and powerful features: **decorators**! ๐Ÿš€ Decorators allow you to modify or enhance functions and methods without changing their core code. Think of them as wrappers that add extra functionality like logging, timing, authentication, and more. They make your code cleaner, more modular, and incredibly reusable! Let's explore how they work with a practical example. ๐Ÿ‘‡

```python
import time

# Our simple decorator function
def timer_decorator(func):
"""
A decorator that measures the execution time of a function.
"""
def wrapper(*args, **kwargs):
start_time = time.time()
print(f"โฑ๏ธ Starting '{func.__name__}'...")
result = func(*args, **kwargs) # Call the original function
end_time = time.time()
print(f"โœ… '{func.__name__}' finished in {end_time - start_time:.4f} seconds.")
return result
return wrapper

# Apply the decorator using the '@' syntax
@timer_decorator
def long_running_function(name):
"""A function that simulates some work."""
print(f"Hello, {name}! Doing some important stuff...")
time.sleep(1.5) # Simulate work for 1.5 seconds
print(f"Done with {name}'s task.")
return f"Task for {name} completed!"

print("--- Calling decorated function ---")
message = long_running_function("Alice")
print(f"Function returned: {message}n")

print("--- Another call with Bob ---")
long_running_function("Bob")
```

Output example:
```
--- Calling decorated function ---
โฑ๏ธ Starting 'long_running_function'...
Hello, Alice! Doing some important stuff...
Done with Alice's task.
โœ… 'long_running_function' finished in 1.5015 seconds.
Function returned: Task for Alice completed!

--- Another call with Bob ---
โฑ๏ธ Starting 'long_running_function'...
Hello, Bob! Doing some important stuff...
Done with Bob's task.
โœ… 'long_running_function' finished in 1.5009 seconds.
```

๐Ÿ’ก **Challenge:** Can you create another decorator, perhaps `log_arguments_decorator`, that prints all the arguments (`*args` and `**kwargs`) passed to the decorated function before it's executed? Apply it to `long_running_function` alongside `timer_decorator`! (Hint: you can stack decorators!). Good luck! ๐Ÿง 

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

Today, we're diving into two fundamental concepts that make your Python code more memory-efficient and elegant: Generators and Iterators! โœจ Learn how to create sequences on-the-fly without storing everything in memory, perfect for large datasets or infinite streams. Get ready to `yield` some amazing results! ๐Ÿ’ช

```python
# Our simple generator function
def countdown(n):
"""A generator that counts down from n to 1."""
print(f"Starting countdown from {n}...")
while n > 0:
yield n # Pauses execution, returns n, and remembers its state
n -= 1
print("Countdown finished!")

# --- Using the generator with next() ---
print("--- Using next() on the generator ---")
my_gen = countdown(3) # Creates a generator object

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

# Trying to get another value would raise a StopIteration error

# --- Using the generator in a for loop ---
print("n--- Using a for loop on the generator ---")
for number in countdown(5):
print(f"Loop value: {number}")
```

Output example:
```
--- Using next() on the generator ---
Starting countdown from 3...
First value: 3
Second value: 2
Third value: 1
--- Using a for loop on the generator ---
Starting countdown from 5...
Loop value: 5
Loop value: 4
Loop value: 3
Loop value: 2
Loop value: 1
Countdown finished!
```

๐Ÿ’ก **Your Challenge:** Create a generator function that yields the first `N` even numbers. How would you then print only the third even number generated using `next()`? ๐Ÿค”

---
Day 22: Generators and Iterators \- Code & Output
๐ŸŒŸ *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 locks? The `with` statement ensures resources are properly acquired and released, even if errors occur. It makes your code cleaner, safer, and much more Pythonic! โœจ Let's explore how it simplifies resource handling.

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

print("--- Using 'with' for file handling ---")

# The 'with' statement ensures the file is automatically closed
# after the block, even if errors occur.
try:
with open("my_notes.txt", "w") as file:
file.write("Hello, Python learners!n")
file.write("Context managers make resource handling easy.n")
# No need for file.close() here!
print("File 'my_notes.txt' written successfully and closed automatically.")

print("n--- Reading content from 'my_notes.txt' ---")
with open("my_notes.txt", "r") as file:
content = file.read()
print(content)
print("File 'my_notes.txt' read successfully and closed automatically.")

except IOError as e:
print(f"An error occurred while handling the file: {e}")

print("--- End of demonstration ---")
```

Output example:
```
--- Using 'with' for file handling ---
File 'my_notes.txt' written successfully and closed automatically.

--- Reading content from 'my_notes.txt' ---
Hello, Python learners!
Context managers make resource handling easy.

File 'my_notes.txt' read successfully and closed automatically.
--- End of demonstration ---
```

**Small Challenge:**
How would you use a `with` statement to ensure a temporary directory is created and then automatically cleaned up after its use? (Hint: Explore the `tempfile` module in Python's standard library!) ๐Ÿงน

---
Day 23: Context Managers \(with statement\) \- Code & Output
๐Ÿš€ Day 24 is here! Today, we're diving into two incredibly powerful and Pythonic features: Lambda Functions and List Comprehensions! โœจ

Lambda functions are small, anonymous functions perfect for quick, one-off operations. List comprehensions offer a super concise and readable way to create lists based on existing iterables. Master these to write cleaner, more efficient Python! ๐Ÿ

```python
# Let's explore Lambda Functions and List Comprehensions!

# Example 1: Lambda Function with map()
# A lambda function is a small anonymous function.
# It can take any number of arguments, but can only have one expression.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(f"Squared numbers (using lambda with map): {squared_numbers}")

# Example 2: List Comprehension
# A concise way to create lists based on existing iterables.
# We'll filter for even numbers and then square them.
numbers_to_process = [10, 15, 20, 25, 30]
even_squared = [x**2 for x in numbers_to_process if x % 2 == 0]
print(f"Even numbers squared (using list comprehension): {even_squared}")

# Another example: Conditional expression in list comprehension
# Create a list of 'Even' or 'Odd' strings
parity_list = ["Even" if n % 2 == 0 else "Odd" for n in range(6)]
print(f"Parity list (using conditional comprehension): {parity_list}")
```

Output example:
```
Squared numbers (using lambda with map): [1, 4, 9, 16, 25]
Even numbers squared (using list comprehension): [100, 400, 900]
Parity list (using conditional comprehension): ['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']
```

Challenge: Can you use a *single* list comprehension to create a list of strings where each string says 'High' if a number is greater than 50, and 'Low' otherwise, for a given list of numbers like `[30, 70, 45, 90, 20]`? Share your solution! ๐Ÿ‘‡
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