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 for Day 57 of the Python learning series!

---

๐Ÿ”ฅ Day 57: Async Seams! ๐Ÿงต Ever wondered how to integrate the speed of `asyncio` into an existing Python codebase full of blocking, synchronous calls? ๐Ÿค” Today, we're diving into 'Asynchronous Seams' โ€“ a crucial technique for gracefully weaving non-blocking I/O into legacy synchronous codebases! โœจ Learn to leverage `asyncio.to_thread()` (or `loop.run_in_executor`) to run blocking operations in a separate thread, keeping your event loop responsive and your application blazing fast. No more freezing your async tasks with a slow database query or a heavy file read!

```python
import asyncio
import time
import functools

# --- Simulate a "legacy" synchronous blocking I/O operation ---
def sync_blocking_io(task_id: int, duration: int):
"""Simulates a blocking operation that takes 'duration' seconds."""
print(f"[{time.time():.2f}] ๐Ÿข Blocking Task {task_id} starting for {duration}s...")
time.sleep(duration) # Simulates a blocking call (e.g., network, disk I/O, heavy computation)
print(f"[{time.time():.2f}] โœ… Blocking Task {task_id} finished.")
return f"Result from Blocking Task {task_id} (duration: {duration}s)"

# --- Regular async tasks ---
async def async_worker(name: str, delay: int):
"""An asynchronous task that pauses for 'delay' seconds."""
print(f"[{time.time():.2f}] ๐Ÿš€ Async Worker {name} starting for {delay}s...")
await asyncio.sleep(delay)
print(f"[{time.time():.2f}] โญ Async Worker {name} finished.")
return f"Result from Async Worker {name} (delay: {delay}s)"

async def main():
print("--- Starting main async process ---")
start_time = time.time()

# We use asyncio.to_thread() (Python 3.9+) to run the blocking function
# in a separate thread, preventing it from blocking the main event loop.
# For older Python versions, you'd typically use:
# loop = asyncio.get_running_loop()
# blocking_task_coro = loop.run_in_executor(None, functools.partial(sync_blocking_io, 1, 3))

blocking_task_coro = asyncio.to_thread(sync_blocking_io, 1, 3)

# Run multiple async tasks and the "threaded" blocking task concurrently
results = await asyncio.gather(
async_worker("A", 1),
async_worker("B", 2),
blocking_task_coro, # The blocking task is now awaitable!
async_worker("C", 0.5)
)

print("n--- All tasks completed ---")
for res in results:
print(f"Final Result: {res}")
print(f"Total elapsed time: {time.time() - start_time:.2f}s")

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

Output example:
```
--- Starting main async process ---
[1678886400.00] ๐Ÿš€ Async Worker A starting for 1s...
[1678886400.00] ๐Ÿš€ Async Worker B starting for 2s...
[1678886400.00] ๐Ÿš€ Async Worker C starting for 0.5s...
[1678886400.00] ๐Ÿข Blocking Task 1 starting for 3s...
[1678886400.50] โญ Async Worker C finished.
[1678886401.00] โญ Async Worker A finished.
[1678886402.00] โญ Async Worker B finished.
[1678886403.00] โœ… Blocking Task 1 finished.

--- All tasks completed ---
Final Result: Result from Async Worker A (delay: 1s)
Final Result: Result from Async Worker B (delay: 2s)
Final Result: Result from Blocking Task 1 (duration: 3s)
Final Result: Result from Async Worker C (delay: 0.5s)
Total elapsed time: 3.00s
```
Notice how the async workers finish *before* the blocking task, even though the blocking task started first. This demonstrates that `asyncio.to_thread` prevented the blocking call from freezing the event loop!

๐Ÿ’ก Small Challenge: Take your `asyncio` skills further! Try wrapping a synchronous network request library (like `requests`) using `asyncio.to_thread` or `run_in_executor` to make an external API call from within an `asyncio` application without blocking the event loop. Share your async masterpiece! ๐Ÿš€

---
Hello Every one WE will Restart from day 1
Here's your Telegram post for Day 3 of the Python learning series!

---

Hey Python Learners! ๐Ÿ‘‹ Ready for Day 3? Today we're diving into the powerful world of *Operators*! ๐Ÿš€ Operators are special symbols that perform operations on values and variables. From basic math to complex logic, they are the building blocks of any program. Let's see how they work and level up our coding skills! ๐Ÿ‘จโ€๐Ÿ’ป

```python
# Day 3: Operators in Python - Let's compute! โœจ

# Arithmetic Operators
a = 10
b = 3
print(f"a + b = {a + b}") # Addition
print(f"a - b = {a - b}") # Subtraction
print(f"a * b = {a * b}") # Multiplication
print(f"a / b = {a / b}") # Division (float result)
print(f"a // b = {a // b}") # Floor Division (integer result)
print(f"a % b = {a % b}") # Modulus (remainder)
print(f"a ** b = {a ** b}") # Exponentiation

# Comparison Operators
x = 5
y = 8
print(f"x == y is {x == y}") # Equal to
print(f"x < y is {x < y}") # Less than
print(f"x >= y is {x >= y}") # Greater than or Equal to

# Logical Operators
is_logged_in = True
has_permission = False
print(f"Logged in AND has permission: {is_logged_in and has_permission}")
print(f"Logged in OR has permission: {is_logged_in or has_permission}")
print(f"NOT logged in: {not is_logged_in}")
```

Output example:
```
a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a // b = 3
a % b = 1
a ** b = 1000
x == y is False
x < y is True
x >= y is False
Logged in AND has permission: False
Logged in OR has permission: True
NOT logged in: False
```

๐Ÿ’ก *Challenge Time!* What will be the output of the expression `(15 % 4) * (2 ** 3) + 7 // 2`? Try it in your interpreter and share your answer! ๐Ÿค” Let's see who gets it right! ๐Ÿ‘‡

---
Day 3: Operators in Python \- Code & Output
What is the output of the following Python expression: `5 * 2 + 8 / 4`?
Anonymous Quiz
0%
12.0
0%
12
0%
7.0
0%
7
๐ŸŽ‰ Day 5: Let's Get Loopy! ๐ŸŽ‰

Ready to make your code work smarter, not harder? Today, we're diving into the powerful world of `for` and `while` loops! ๐Ÿ”„ These fundamental tools allow your programs to repeat tasks, iterate through collections, and automate workflows effortlessly. Master them, and unlock a new level of Python proficiency! โœจ Let's loop into action! ๐Ÿ‘‡

```python
# --- Example 1: The 'for' Loop ---
print("Counting with 'for' loop:")
for i in range(1, 4): # Loops from 1 up to (but not including) 4
print(f"Number: {i}")

fruits = ["apple", "banana", "cherry"]
print("nIterating through a list with 'for' loop:")
for fruit in fruits:
print(f"I like {fruit}!")

# --- Example 2: The 'while' Loop ---
print("nCounting down with 'while' loop:")
count = 3
while count > 0:
print(f"T-minus {count}...")
count -= 1 # Decrement count by 1
print("Liftoff! ๐Ÿš€")
```

Output example:
```
Counting with 'for' loop:
Number: 1
Number: 2
Number: 3

Iterating through a list with 'for' loop:
I like apple!
I like banana!
I like cherry!

Counting down with 'while' loop:
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! ๐Ÿš€
```

๐Ÿ’ก Your turn! Can you use a `for` loop to print all even numbers from 2 to 10 (inclusive)? Or use a `while` loop to continuously ask a user for their favorite color until they type "exit"? Share your code! ๐Ÿ‘‡

---
Day 5: Loops \(for and while\) \- Code & Output
What will be the output of the following Python code snippet?
```python
counter = 0 while counter < 4: print(counter) counter += 1 ```
Anonymous Quiz
0%
0 1 2 3
0%
1 2 3 4
0%
0 1 2 3 4
0%
The code will result in an infinite loop.
๐Ÿ‘‹ Hey Python Learners!

Welcome to **Day 6** of our Python journey! ๐Ÿš€ Today, we're diving into one of the most fundamental and powerful concepts in programming: **Functions**.

Functions are reusable blocks of code that perform a specific task. They help organize your code, make it more readable, and save you from repeating yourself (DRY - Don't Repeat Yourself principle!). Think of them as mini-programs within your main program. Let's see how to define and use them!

```python
# Define a simple function to greet someone
def greet_user(name):
"""This function takes a name and prints a greeting."""
print(f"Hello, {name}! Welcome to Day 6. ๐Ÿ‘‹")

# Define a function that adds two numbers and returns the result
def add_numbers(num1, num2):
"""This function adds two numbers and returns their sum."""
return num1 + num2

# Call the greet_user function
greet_user("Alice")
greet_user("Bob")

# Call the add_numbers function and store the result
result = add_numbers(10, 5)
print(f"The sum of 10 and 5 is: {result}")

# You can also call it directly in a print statement
print(f"Adding 7 and 3 gives: {add_numbers(7, 3)}")
```

Output example:
```
Hello, Alice! Welcome to Day 6. ๐Ÿ‘‹
Hello, Bob! Welcome to Day 6. ๐Ÿ‘‹
The sum of 10 and 5 is: 15
Adding 7 and 3 gives: 10
```

---

### ๐Ÿ”ฅ Small Challenge:
Write a Python function called `calculate_area` that takes two arguments: `length` and `width`. The function should return the product of these two numbers (the area of a rectangle). Then, call your function with example values and print the result!

---

๐Ÿ’ก Keep practicing, and you'll master functions in no time! See you tomorrow for Day 7! #PythonLearning #Functions #PythonBasics #CodingChallenge
Day 6: Functions in Python \- Code & Output
Which keyword is used to define a function in Python?
Anonymous Quiz
0%
func
0%
define
0%
def
0%
function
Here's your Telegram post for Day 7 of the Python learning series!

---

๐Ÿ‘‹ Day 7 of our Python journey is here! Today, we're diving into two fundamental data structures: **Lists** ๐Ÿ“ and **Tuples** ๐Ÿง.

Lists are like flexible shopping carts ๐Ÿ›’ - ordered, changeable, and you can add or remove items easily. Tuples, on the other hand, are like sealed time capsules ๐Ÿ•ฐ๏ธ - ordered, but once created, their contents cannot be changed. Understanding their differences is key to writing efficient Python code! Let's explore!

```python
# --- Lists: Mutable collections ---
my_list = ["apple", "banana", "cherry"]
print(f"Original List: {my_list}")

# Add an element
my_list.append("date")
print(f"List after append: {my_list}")

# Modify an element
my_list[0] = "apricot"
print(f"List after modification: {my_list}")

# Access an element
print(f"Second item in list: {my_list[1]}")
print(f"List length: {len(my_list)}")

print("-" * 20)

# --- Tuples: Immutable collections ---
my_tuple = ("red", "green", "blue")
print(f"Original Tuple: {my_tuple}")

# Access an element
print(f"First item in tuple: {my_tuple[0]}")
print(f"Tuple length: {len(my_tuple)}")

# Uncommenting the line below would cause an error (TypeError)
# my_tuple[0] = "purple" # Tuples cannot be modified after creation!
# print(f"Attempted tuple modification (will raise error): {my_tuple}")
```

Output example:
```
Original List: ['apple', 'banana', 'cherry']
List after append: ['apple', 'banana', 'cherry', 'date']
List after modification: ['apricot', 'banana', 'cherry', 'date']
Second item in list: banana
List length: 4
--------------------
Original Tuple: ('red', 'green', 'blue')
First item in tuple: red
Tuple length: 3
```

๐Ÿš€ **Your Challenge:**
1. Create a list called `my_favorite_movies` with 3 movie titles.
2. Add another movie to your `my_favorite_movies` list.
3. Access and print the first movie in your list.
4. Create a tuple called `my_birth_date` with your birth year, month, and day (e.g., `(1990, 5, 15)`). Can you change any part of `my_birth_date`? ๐Ÿค”

---
Day 7: Lists and Tuples \- Code & Output
Here's your Telegram post for Day 8 of the Python learning series!

---

๐Ÿš€ **Day 8: Unlocking Dictionaries & Sets!** ๐Ÿง 

Today, we're diving into two incredibly powerful and versatile data structures in Python: **Dictionaries** and **Sets**!

**Dictionaries** allow you to store data in `key: value` pairs. Think of them like a real-world dictionary where words (keys) map directly to their definitions (values). They're perfect for fast data retrieval and organizing information logically.

**Sets**, on the other hand, are collections of unique elements. If you have a list with duplicates and want only the distinct items, or need to perform mathematical set operations like union or intersection, sets are your go-to!

Let's see them in action! ๐Ÿ‘‡

```python
# --- Dictionaries: Key-Value Pairs ---
print("--- Dictionary Example ---")

# Creating a dictionary
student_profile = {
"name": "Alice",
"age": 20,
"major": "Computer Science",
"courses": ["Python", "Data Structures"]
}

print(f"Student Name: {student_profile['name']}")
print(f"Student Age: {student_profile.get('age', 'N/A')}") # Safer access with .get()

# Modifying and adding elements
student_profile["age"] = 21 # Update an existing value
student_profile["university"] = "Tech University" # Add a new key-value pair
print(f"Updated Profile: {student_profile}")

print(f"All Keys: {list(student_profile.keys())}")
print(f"All Values: {list(student_profile.values())}")


# --- Sets: Unique Elements ---
print("n--- Set Example ---")

# Creating a set (duplicates are automatically removed)
my_numbers = {1, 2, 3, 4, 3, 2}
print(f"Original set (duplicates removed): {my_numbers}")

# Adding elements to a set
my_numbers.add(5)
my_numbers.add(1) # Adding an existing element has no effect
print(f"Set after adding 5: {my_numbers}")

# Removing elements
my_numbers.remove(2) # Raises KeyError if element not found
print(f"Set after removing 2: {my_numbers}")

# Set operations
even_numbers = {2, 4, 6, 8}
prime_numbers = {2, 3, 5, 7}

# Union: all unique elements from both sets
print(f"Union with even numbers: {my_numbers.union(even_numbers)}")

# Intersection: common elements in both sets
print(f"Intersection with prime numbers: {my_numbers.intersection(prime_numbers)}")
```

Output example:
```
--- Dictionary Example ---
Student Name: Alice
Student Age: 20
Updated Profile: {'name': 'Alice', 'age': 21, 'major': 'Computer Science', 'courses': ['Python', 'Data Structures'], 'university': 'Tech University'}
All Keys: ['name', 'age', 'major', 'courses', 'university']
All Values: ['Alice', 21, 'Computer Science', ['Python', 'Data Structures'], 'Tech University']

--- Set Example ---
Original set (duplicates removed): {1, 2, 3, 4}
Set after adding 5: {1, 2, 3, 4, 5}
Set after removing 2: {1, 3, 4, 5}
Union with even numbers: {1, 2, 3, 4, 5, 6, 8}
Intersection with prime numbers: {3, 5}
```

๐Ÿ’ก **Your Challenge!**
Create a dictionary for your favorite movie, storing its `title`, `director`, `release_year`, and `genres` (as a list). Then, create a set of all unique genres you enjoy. Can you add a new genre to your set and update the movie's release year in the dictionary? Share your code snippet! ๐Ÿ‘‡

---
Day 8: Dictionaries and Sets \- Code & Output
โœจ Day 9 of our Python journey! โœจ Today, we're diving into the incredibly powerful world of *String Manipulation*! ๐Ÿ Strings are fundamental, and knowing how to slice, dice, transform, and clean them is a super valuable skill for handling text data. Get ready to master methods like `upper()`, `lower()`, `replace()`, `split()`, and more. Let's make our text data sing! ๐ŸŽถ

```python
message = " Hello, Python Learners! Welcome to Day 9! "

print(f"Original string: '{message}'")
print(f"Length of original: {len(message)}")

# 1. Stripping whitespace from ends
cleaned_message = message.strip()
print(f"Stripped string: '{cleaned_message}'")

# 2. Converting case
print(f"Uppercase: {cleaned_message.upper()}")
print(f"Lowercase: {cleaned_message.lower()}")

# 3. Slicing parts of the string
print(f"First 5 characters: {cleaned_message[0:5]}")
print(f"Last 5 characters: {cleaned_message[-5:]}")
print(f"Substring 'Python': {cleaned_message[7:13]}") # Extracts "Python"

# 4. Replacing parts of the string
new_message = cleaned_message.replace("Day 9", "String Manipulation Day")
print(f"After replacement: {new_message}")

# 5. Splitting the string into a list
words = new_message.split(" ")
print(f"Split by space: {words}")

sentence_parts = cleaned_message.split("!")
print(f"Split by '!': {sentence_parts}")
```

Output example:
```
Original string: ' Hello, Python Learners! Welcome to Day 9! '
Length of original: 45
Stripped string: 'Hello, Python Learners! Welcome to Day 9!'
Uppercase: HELLO, PYTHON LEARNERS! WELCOME TO DAY 9!
Lowercase: hello, python learners! welcome to day 9!
First 5 characters: Hello
Last 5 characters: Day 9!
Substring 'Python': Python
After replacement: Hello, Python Learners! Welcome to String Manipulation Day!
Split by space: ['Hello,', 'Python', 'Learners!', 'Welcome', 'to', 'String', 'Manipulation', 'Day!']
Split by '!': ['Hello, Python Learners', ' Welcome to Day 9', '']
```

๐Ÿš€ **Small Challenge:** Can you write a Python one-liner to reverse the `cleaned_message` string (`'Hello, Python Learners! Welcome to Day 9!'`)? Share your solution in the comments! ๐Ÿ‘‡

---
Day 9: String Manipulation \- Code & Output