Which special method within a Python descriptor is responsible for defining the behavior when an attribute is *assigned* (e.g., `instance.attribute = value`)?
Anonymous Quiz
0%
__get__(self, instance, owner)
0%
__set__(self, instance, value)
0%
__set_name__(self, owner, name)
0%
__init__(self, name)
๐ **Day 56: Surgical Code Transformation with Python AST!** ๐ Ever wondered what happens *behind the scenes* when Python executes your code? The Abstract Syntax Tree (AST) is your answer! It's a fundamental, hierarchical representation of your code's structure. Today, we're not just looking at it; we're *hacking* it! ๐ ๏ธ Learn to programmatically analyze, modify, and even generate Python code by manipulating its AST. Unlock powerful capabilities for linters, refactoring tools, and advanced metaprogramming! Get ready to dissect your code like never before. ๐ก
```python
import ast
# 1. Original code as a string
original_code_str = """
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 5 # Let's change this '5'
return total
"""
print("--- Original Code ---")
print(original_code_str)
# 2. Parse the code into an AST
tree = ast.parse(original_code_str)
# 3. Define a custom NodeTransformer to modify the AST
class ConstantModifier(ast.NodeTransformer):
"""
Changes all integer constants with value '5' to '500'.
"""
def visit_Constant(self, node):
# ast.Constant is used for literals like numbers, strings, etc. (Python 3.8+)
if isinstance(node.value, int) and node.value == 5:
# Create a new Constant node with the desired value
return ast.Constant(value=500, kind=None)
# For all other nodes, ensure children are visited
return self.generic_visit(node)
# 4. Apply the transformer to modify the AST
modified_tree = ConstantModifier().visit(tree)
# 5. Unparse the modified AST back into a code string
modified_code_str = ast.unparse(modified_tree)
print("n--- Modified Code AST ---")
print(modified_code_str)
# 6. Execute both versions of the code to see the difference
print("n--- Execution Results ---")
# Execute original code
exec_globals_original = {}
exec(original_code_str, exec_globals_original)
original_calculate_price = exec_globals_original['calculate_price']
print(f"calculate_price(2) (original): {original_calculate_price(2)}") # Expected: (10*2)+5 = 25
# Execute modified code
exec_globals_modified = {}
exec(modified_code_str, exec_globals_modified)
modified_calculate_price = exec_globals_modified['calculate_price']
print(f"calculate_price(2) (modified): {modified_calculate_price(2)}") # Expected: (10*2)+500 = 520
```
Output example:
```
--- Original Code ---
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 5 # Let's change this '5'
return total
--- Modified Code AST ---
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 500
return total
--- Execution Results ---
calculate_price(2) (original): 25
calculate_price(2) (modified): 520
```
**Small Challenge:**
Instead of changing a constant, can you modify the `calculate_price` function's AST to accept an additional argument `tax_rate` and add `total * tax_rate` to the return value? ๐คฏ (Hint: You'll need to add a new `arg` to `FunctionDef.args.args` and modify the `Return` statement's `value` to be a new `BinOp`). Share your solution! ๐ง
---
```python
import ast
# 1. Original code as a string
original_code_str = """
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 5 # Let's change this '5'
return total
"""
print("--- Original Code ---")
print(original_code_str)
# 2. Parse the code into an AST
tree = ast.parse(original_code_str)
# 3. Define a custom NodeTransformer to modify the AST
class ConstantModifier(ast.NodeTransformer):
"""
Changes all integer constants with value '5' to '500'.
"""
def visit_Constant(self, node):
# ast.Constant is used for literals like numbers, strings, etc. (Python 3.8+)
if isinstance(node.value, int) and node.value == 5:
# Create a new Constant node with the desired value
return ast.Constant(value=500, kind=None)
# For all other nodes, ensure children are visited
return self.generic_visit(node)
# 4. Apply the transformer to modify the AST
modified_tree = ConstantModifier().visit(tree)
# 5. Unparse the modified AST back into a code string
modified_code_str = ast.unparse(modified_tree)
print("n--- Modified Code AST ---")
print(modified_code_str)
# 6. Execute both versions of the code to see the difference
print("n--- Execution Results ---")
# Execute original code
exec_globals_original = {}
exec(original_code_str, exec_globals_original)
original_calculate_price = exec_globals_original['calculate_price']
print(f"calculate_price(2) (original): {original_calculate_price(2)}") # Expected: (10*2)+5 = 25
# Execute modified code
exec_globals_modified = {}
exec(modified_code_str, exec_globals_modified)
modified_calculate_price = exec_globals_modified['calculate_price']
print(f"calculate_price(2) (modified): {modified_calculate_price(2)}") # Expected: (10*2)+500 = 520
```
Output example:
```
--- Original Code ---
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 5 # Let's change this '5'
return total
--- Modified Code AST ---
def calculate_price(quantity):
base_price = 10
total = base_price * quantity + 500
return total
--- Execution Results ---
calculate_price(2) (original): 25
calculate_price(2) (modified): 520
```
**Small Challenge:**
Instead of changing a constant, can you modify the `calculate_price` function's AST to accept an additional argument `tax_rate` and add `total * tax_rate` to the return value? ๐คฏ (Hint: You'll need to add a new `arg` to `FunctionDef.args.args` and modify the `Return` statement's `value` to be a new `BinOp`). Share your solution! ๐ง
---
What is the primary purpose of Python's `ast` module?
Anonymous Quiz
0%
To manage memory allocation for Python objects.
0%
To compile Python code into machine language for faster execution.
0%
To represent Python source code as a tree of objects for programmatic analysis and transformation.
0%
To facilitate inter-process communication within a Python application.
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! ๐
---
---
๐ฅ 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! ๐
---
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! ๐
---
---
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! ๐
---
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! ๐
---
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! ๐
---
What will be the output of the following Python code snippet?
```python
counter = 0 while counter < 4: print(counter) counter += 1 ```
```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
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
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 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`? ๐ค
---
Which of the following statements about Python lists and tuples is true?
Anonymous Quiz
0%
Lists are immutable, and tuples are mutable.
0%
Both lists and tuples are mutable.
100%
Lists are mutable, and tuples are immutable.
0%
Both lists and tuples are immutable.
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: 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! ๐
---
Which of the following statements about Python dictionaries is TRUE?
Anonymous Quiz
0%
Dictionary keys must be integers.
0%
Dictionaries store data in an ordered sequence.
0%
Dictionary values must be unique.
0%
Dictionary keys must be unique.
โจ 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! ๐
---
```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! ๐
---