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
In regular expressions (RegEx), what does the pattern `\d` typically match?
Anonymous Quiz
0%
Any character
0%
Any whitespace character
0%
Any digit (0-9)
0%
Any non-digit character
🎉 **Day 19: Virtual Environments!** 🎉

Ever found yourself in "dependency hell" where one project's requirements clash with another's? 🤯 Python virtual environments are your ultimate lifesaver! They create isolated spaces for each project, ensuring that dependencies for one don't interfere with another. Today, we'll master `venv` to keep your projects clean, consistent, and conflict-free. Get ready to streamline your workflow like a pro! 🐍✨📦

---

```python
# 1. Create a virtual environment named 'myproject_env'
# (Run this command in your project's root directory)
python3 -m venv myproject_env

# 2. Activate the virtual environment
# On Linux/macOS:
source myproject_env/bin/activate

# On Windows (Command Prompt):
# myproject_envScriptsactivate.bat

# On Windows (PowerShell):
# myproject_envScriptsActivate.ps1

# 3. Once activated, your terminal prompt will show the environment name.
# Now, any package you install with 'pip' will be confined to THIS environment.
# (myproject_env) pip install requests

# 4. When you're done working in the environment, deactivate it:
# (myproject_env) deactivate
```

---

Output example:

```
# After running 'python3 -m venv myproject_env':
# (No direct output, creates the directory)

# After running 'source myproject_env/bin/activate':
(myproject_env) user@host:~/your_project$

# After running '(myproject_env) pip install requests':
(myproject_env) user@host:~/your_project$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 KB 1.1 MB/s eta 0:00:00
... (other dependency installations)
Successfully installed charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0

# After running '(myproject_env) deactivate':
user@host:~/your_project$
```

---

🚀 **Your Challenge Today:**
1. Create a new directory for a project (e.g., `my_flask_app`).
2. Navigate into that directory.
3. Create a virtual environment called `flask_env` inside it.
4. Activate `flask_env`.
5. Install the `flask` library (`pip install flask`) within this environment.
6. Verify that `flask` is indeed installed by running `pip list`.
7. Deactivate the environment.

Share your success! 👇

---
Day 19: Virtual Environments \- Code & Output
🚀 **Day 20: Working with Dates and Times in Python!** ⏰

Hello Python adventurers! Today, we're unlocking the secrets of time with Python's incredibly useful `datetime` module. 🗓️ From logging events to scheduling tasks or analyzing time-series data, mastering dates and times is a fundamental skill. We'll learn how to grab the current moment, format it just the way we like, parse date strings, and even perform time-based calculations. Let's make time management simple! ✨

```python
from datetime import datetime, timedelta

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

# Format the datetime object into a specific string
# %Y - Year, %m - Month, %d - Day, %H - Hour (24-hour), %M - Minute, %S - Second
formatted_string = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date & Time: {formatted_string}")

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

# Perform date arithmetic using timedelta
future_time = current_time + timedelta(days=5, hours=2, minutes=30)
print(f"5 days, 2 hours, 30 minutes from now: {future_time}")
```

Output example:
```
Current Date & Time: 2024-07-20 12:34:56.789012
Formatted Date & Time: 2024-07-20 12:34:56
Parsed Date from string: 2024-07-20 10:00:00
5 days, 2 hours, 30 minutes from now: 2024-07-25 14:04:56.789012
```

💡 **Challenge:**
Write a Python script that calculates and prints your exact age in days from your birthdate to today! 🎂 Don't forget to use `timedelta`! Share your solution in the comments! 👇

---
Day 20: Working with Dates and Times \- Code & Output
Which `datetime` method is primarily used to format a `datetime` object into a human-readable string?
Anonymous Quiz
0%
datetime.strptime()
0%
datetime.strftime()
0%
datetime.to_string()
✨ **Python Learning Series - Day 21: Decorators** ✨

Ready to level up your Python skills? Today we dive into `Decorators`! 🚀

Decorators are powerful syntactic sugar that allow you to modify or enhance other functions without changing their source code. Think of them as functions that wrap around other functions, adding extra functionality before or after the original function executes. They're incredibly useful for logging, authentication, performance measurement, and more, helping you write cleaner, more reusable code! 🛠️

```python
def log_execution(func):
"""A decorator that logs when a function starts and finishes."""
def wrapper(*args, **kwargs):
print(f"🚀 Calling function: {func.__name__}")
result = func(*args, **kwargs)
print(f"✅ Finished function: {func.__name__}")
return result
return wrapper

@log_execution
def greet(name):
"""A simple function to greet someone."""
print(f"Hello, {name}!")
return f"Greeting for {name}"

@log_execution
def add_numbers(a, b):
"""Adds two numbers and returns the sum."""
print(f"Adding {a} and {b}...")
return a + b

# Call the decorated functions
greet("Alice")
print("-" * 20)
sum_result = add_numbers(10, 5)
print(f"Sum result: {sum_result}")
```

Output example:
```
🚀 Calling function: greet
Hello, Alice!
✅ Finished function: greet
--------------------
🚀 Calling function: add_numbers
Adding 10 and 5...
✅ Finished function: add_numbers
Sum result: 15
```

**Small Challenge:** Can you create a decorator that measures and prints the execution time of any function it wraps? (Hint: The `time` module might be useful! `time.time()`)

---
Day 21: Decorators \- Code & Output
Hello Python Learners! 👋

It's **Day 22** of our Python journey, and today we're diving into some advanced but incredibly useful concepts: **Generators and Iterators**! 🚀

Ever wondered how Python handles huge datasets without hogging all your memory? That's where these come in! Iterators give you a way to access elements one by one, while generators are a super-convenient way to create iterators, making your code more memory-efficient and performant by generating values on-the-fly, only when needed. Think "lazy evaluation" – powerful stuff! Let's see them in action. 👇

```python
# --- Understanding Iterators ---
# An iterator is an object that can be iterated upon.
# It implements __iter__() and __next__() methods.
class MyRangeIterator:
def __init__(self, start, end):
self.current = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.current <= self.end:
value = self.current
self.current += 1
return value
else:
raise StopIteration

print("--- Custom Iterator (MyRangeIterator) ---")
for num in MyRangeIterator(1, 3):
print(f"Iterator value: {num}")

# --- Understanding Generators ---
# Generators are functions that use the 'yield' keyword.
# They produce a sequence of results instead of a single value.
# Each 'yield' statement pauses the function and saves its state.
def simple_generator(start, end):
current = start
while current <= end:
yield current # Pause here, return 'current', resume later
current += 1

print("n--- Simple Generator ---")
gen_obj = simple_generator(1, 3)
print(f"Generator object: {gen_obj}")
for val in gen_obj:
print(f"Generator value: {val}")

# Another common use: infinite sequences or data streams
def infinite_sequence():
num = 0
while True:
yield num
num += 1

print("n--- Infinite Sequence (first 5) ---")
inf_gen = infinite_sequence()
for _ in range(5):
print(f"Infinite value: {next(inf_gen)}")

```

Output example:
```
--- Custom Iterator (MyRangeIterator) ---
Iterator value: 1
Iterator value: 2
Iterator value: 3

--- Simple Generator ---
Generator object: <generator object simple_generator at 0x...>
Generator value: 1
Generator value: 2
Generator value: 3

--- Infinite Sequence (first 5) ---
Infinite value: 0
Infinite value: 1
Infinite value: 2
Infinite value: 3
Infinite value: 4
```

🔥 **Small Challenge:**
Modify the `simple_generator` function to yield only **even numbers** within a given range. Or, create a generator that yields the first `n` terms of the Fibonacci sequence! Share your code! 🧑‍💻

---
Day 22: Generators and Iterators \- Code & Output
✨🐍 **Python Learning Series - Day 23: Context Managers (with statement)!** 📚

Today, we're diving into the incredibly powerful `with` statement! 💪 This Pythonic gem simplifies resource management, ensuring that resources like files, network connections, or database locks are properly acquired and, most importantly, *reliably released*, even if errors occur. No more forgotten `.close()` calls! The `with` statement handles the setup (`__enter__`) and teardown (`__exit__`) for you, making your code cleaner and safer. ✅ Let's explore!

```python
print("--- File Handling Example ---")
file_name = "day23_notes.txt"

try:
# Using 'with' to open a file for writing
# The file will be automatically closed when the 'with' block exits
with open(file_name, "w") as f:
f.write("Day 23: Exploring Python Context Managers.n")
f.write("The 'with' statement simplifies resource management significantly!n")
print(f"Content successfully written to '{file_name}'.")

# Using 'with' to open a file for reading
with open(file_name, "r") as f:
content = f.read()
print(f"nContent read from '{file_name}':")
print(content.strip())

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

Output example:
```
--- File Handling Example ---
Content successfully written to 'day23_notes.txt'.

Content read from 'day23_notes.txt':
Day 23: Exploring Python Context Managers.
The 'with' statement simplifies resource management significantly!
```

💡 **Your Challenge:**
Create a *simple custom context manager* using a class with `__enter__` and `__exit__` methods. Make `__enter__` print "Resource acquired!" and `__exit__` print "Resource released!". Then, use it with a `with` statement and show the output! 👇

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

---

🚀 Python Learning Series - Day 24! ✨ Today, we're unlocking two incredibly powerful and Pythonic features: Lambda Functions and List Comprehensions! 💡 Lambda functions let you create small, anonymous, single-expression functions on the fly. List comprehensions offer a concise and efficient way to create lists. Master these, and your Python code will become much cleaner and more efficient! Let's dive in! 📚

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

# --- Lambda Functions ---
# 1. Simple lambda function
add_five = lambda x: x + 5
print(f"Lambda: 10 + 5 = {add_five(10)}")

# 2. Using lambda with map() to apply a function to all items
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(f"Map with lambda (squared): {squared_numbers}")

# 3. Using lambda with filter() to select items
filtered_list = list(filter(lambda x: x > 3, numbers))
print(f"Filter with lambda (numbers > 3): {filtered_list}")

# --- List Comprehensions ---
# 4. Basic list comprehension (squares)
squares_lc = [x**2 for x in range(1, 6)]
print(f"List comprehension (squares 1-5): {squares_lc}")

# 5. List comprehension with a condition (even numbers)
even_numbers_lc = [num for num in numbers if num % 2 == 0]
print(f"List comprehension (even numbers): {even_numbers_lc}")
```

Output example:
```
Lambda: 10 + 5 = 15
Map with lambda (squared): [1, 4, 9, 16, 25]
Filter with lambda (numbers > 3): [4, 5]
List comprehension (squares 1-5): [1, 4, 9, 16, 25]
List comprehension (even numbers): [2, 4]
```

💡 Small Challenge: From our `numbers` list, create a new list containing only numbers greater than 2, and then cube each of those numbers. Try to achieve this in a single line using a *list comprehension*! Can you also think about how `map` and `filter` with *lambda functions* could achieve the same result?

---
Day 24: Lambda Functions and List Comprehensions \- Code & Output
Which of the following is the most concise and Pythonic way to create a list containing the squares of numbers from 0 to 4 (i.e., [0, 1, 4, 9, 16])?
Anonymous Quiz
0%
[x**2 for x in range(5)]
0%
squares = [] for x in range(5): squares.append(x**2)
0%
list(map(lambda x: x**2, range(5)))
0%
[x*x for x in [0, 1, 2, 3, 4]]
Here's your Telegram post for Day 25: Unit Testing!

---

🚀 Day 25: Master Unit Testing in Python! 🚀

Ever wondered how to ensure your code works perfectly every time? 🤔 Today, we dive into Unit Testing – a crucial practice for writing robust and bug-free applications. We'll use Python's built-in `unittest` module to create and run tests for our functions. Get ready to build confidence in your code! 💪 Let's make our programs reliable! ✨

First, create a file named `calculator.py`:
```python
# calculator.py
def add(a, b):
"""Adds two numbers and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a + b

def subtract(a, b):
"""Subtracts b from a and returns the result."""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both inputs must be numbers.")
return a - b
```

Now, create a file named `test_calculator.py` in the same directory:
```python
# test_calculator.py
import unittest
from calculator import add, subtract

class TestCalculator(unittest.TestCase):

def test_add(self):
"""Test the add function with various valid inputs."""
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(-1, -1), -2)
self.assertEqual(add(0, 0), 0)
self.assertAlmostEqual(add(0.1, 0.2), 0.3)

def test_subtract(self):
"""Test the subtract function with various valid inputs."""
self.assertEqual(subtract(5, 3), 2)
self.assertEqual(subtract(3, 5), -2)
self.assertEqual(subtract(0, 0), 0)
self.assertEqual(subtract(-1, -1), 0)
self.assertEqual(subtract(10, 0), 10)

def test_add_type_error(self):
"""Test add function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
add(1, "2")
with self.assertRaises(TypeError):
add("a", 2)
with self.assertRaises(TypeError):
add(None, 5)

def test_subtract_type_error(self):
"""Test subtract function for TypeError with invalid inputs."""
with self.assertRaises(TypeError):
subtract(1, "2")
with self.assertRaises(TypeError):
subtract("a", 2)

if __name__ == '__main__':
unittest.main()
```

To run the tests, navigate to the directory containing these files in your terminal and execute:
`python -m unittest test_calculator.py`

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

OK
```

💡 **Your Challenge:**
Modify `calculator.py` to include a `multiply(a, b)` function. Don't forget to add type checking! Then, add a new test method `test_multiply` within `TestCalculator` in `test_calculator.py` to thoroughly test your new function with both valid and invalid inputs! Share your solution in the comments! 👇

---
Day 25: Unit Testing \- Code & Output