Here's your Telegram post and quiz question!
---
🚀 Day 4: Time to make your Python programs smart! Today, we're mastering *Conditional Statements*: `if`, `elif`, and `else`. 🤖 These powerful tools let your code make decisions and execute different blocks of instructions based on specific conditions. No more rigid scripts – let's add some flexible logic! Get ready to control the flow of your programs like a pro! 👇
```python
# Day 4: Conditional Statements (if, elif, else)
# Get a score from the user
score = int(input("Enter your test score (0-100): "))
# Use if, elif, else to assign a grade based on the score
if score >= 90:
print("🎉 Excellent! You got an A!")
elif score >= 75:
print("👍 Good job! You got a B.")
elif score >= 50:
print("✅ You passed! Keep practicing.")
else:
print("🙁 Needs improvement. Don't give up!")
print("Program finished.")
```
Output example:
```
Enter your test score (0-100): 78
👍 Good job! You got a B.
Program finished.
```
✨ **Your Challenge:** Modify the code above! Add an `elif` condition to print 'Amazing!' if the score is exactly 100. How would you adjust the existing `if score >= 90` condition to fit this new rule? 🤔
---
---
🚀 Day 4: Time to make your Python programs smart! Today, we're mastering *Conditional Statements*: `if`, `elif`, and `else`. 🤖 These powerful tools let your code make decisions and execute different blocks of instructions based on specific conditions. No more rigid scripts – let's add some flexible logic! Get ready to control the flow of your programs like a pro! 👇
```python
# Day 4: Conditional Statements (if, elif, else)
# Get a score from the user
score = int(input("Enter your test score (0-100): "))
# Use if, elif, else to assign a grade based on the score
if score >= 90:
print("🎉 Excellent! You got an A!")
elif score >= 75:
print("👍 Good job! You got a B.")
elif score >= 50:
print("✅ You passed! Keep practicing.")
else:
print("🙁 Needs improvement. Don't give up!")
print("Program finished.")
```
Output example:
```
Enter your test score (0-100): 78
👍 Good job! You got a B.
Program finished.
```
✨ **Your Challenge:** Modify the code above! Add an `elif` condition to print 'Amazing!' if the score is exactly 100. How would you adjust the existing `if score >= 90` condition to fit this new rule? 🤔
---
What will be the output of the following Python code snippet?
```python
number = 10 if number > 15: message = "High" elif number == 10: message = "Exact" elif number < 12: message = "Low" else: message = "Other" print(message) ```
```python
number = 10 if number > 15: message = "High" elif number == 10: message = "Exact" elif number < 12: message = "Low" else: message = "Other" print(message) ```
Anonymous Quiz
0%
High
100%
Exact
0%
Low
0%
Other
Here's your Telegram post for Day 5 of the Python learning series!
---
**Day 5: Loops (for and while) 🔄**
Hello, Python learners! 👋 Today we're diving into the powerful world of loops! Loops are absolutely essential for automating repetitive tasks and making your code super efficient. We'll explore two main types: `for` loops, perfect for iterating over sequences like lists or ranges, and `while` loops, which repeat as long as a certain condition remains true. Get ready to automate! 🚀
```python
# --- Python Loops: for and while ---
print("--- For Loop Example (Iterating over a list) ---")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")
print("n--- While Loop Example (Counting) ---")
count = 0
while count < 3:
print(f"Count is {count}")
count += 1 # IMPORTANT: Increment to avoid an infinite loop!
print("n--- For Loop with range() ---")
for i in range(4): # This will iterate for i = 0, 1, 2, 3
print(f"Number from range: {i}")
print("n--- For Loop with else (optional!) ---")
for char_code in [65, 66, 67]:
print(f"Character: {chr(char_code)}")
else:
print("All characters processed!")
```
Output example:
```
--- For Loop Example (Iterating over a list) ---
I love apple!
I love banana!
I love cherry!
--- While Loop Example (Counting) ---
Count is 0
Count is 1
Count is 2
--- For Loop with range() ---
Number from range: 0
Number from range: 1
Number from range: 2
Number from range: 3
--- For Loop with else (optional!) ---
Character: A
Character: B
Character: C
All characters processed!
```
💡 **Your Challenge:**
1. Use a `while` loop to print numbers from 5 down to 1.
2. Then, use a `for` loop to print each character in the word "Python" on a separate line.
Share your solutions or questions in the comments! 👇 Happy coding! ✨
---
---
**Day 5: Loops (for and while) 🔄**
Hello, Python learners! 👋 Today we're diving into the powerful world of loops! Loops are absolutely essential for automating repetitive tasks and making your code super efficient. We'll explore two main types: `for` loops, perfect for iterating over sequences like lists or ranges, and `while` loops, which repeat as long as a certain condition remains true. Get ready to automate! 🚀
```python
# --- Python Loops: for and while ---
print("--- For Loop Example (Iterating over a list) ---")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")
print("n--- While Loop Example (Counting) ---")
count = 0
while count < 3:
print(f"Count is {count}")
count += 1 # IMPORTANT: Increment to avoid an infinite loop!
print("n--- For Loop with range() ---")
for i in range(4): # This will iterate for i = 0, 1, 2, 3
print(f"Number from range: {i}")
print("n--- For Loop with else (optional!) ---")
for char_code in [65, 66, 67]:
print(f"Character: {chr(char_code)}")
else:
print("All characters processed!")
```
Output example:
```
--- For Loop Example (Iterating over a list) ---
I love apple!
I love banana!
I love cherry!
--- While Loop Example (Counting) ---
Count is 0
Count is 1
Count is 2
--- For Loop with range() ---
Number from range: 0
Number from range: 1
Number from range: 2
Number from range: 3
--- For Loop with else (optional!) ---
Character: A
Character: B
Character: C
All characters processed!
```
💡 **Your Challenge:**
1. Use a `while` loop to print numbers from 5 down to 1.
2. Then, use a `for` loop to print each character in the word "Python" on a separate line.
Share your solutions or questions in the comments! 👇 Happy coding! ✨
---
What will be the output of the following Python code snippet?
```python result = "" for i in range(4): if i == 2: break result += str(i) print(result) ```
```python result = "" for i in range(4): if i == 2: break result += str(i) print(result) ```
Anonymous Quiz
0%
012
50%
01
50%
0123
0%
0
🚀 **Python Learning Series - Day 6: Functions in Python!** 🚀
Hello, amazing learners! ✨ Today, we're diving into one of the most fundamental and powerful concepts in Python: **Functions**! Functions allow us to write reusable blocks of code, making our programs organized, efficient, and easier to understand. No more repetitive code! Let's unlock the magic of `def`! 🔑
---
```python
# 1. Defining a simple function
def greet_user(name):
"""This function greets the user by name."""
print(f"Hello, {name}! Welcome to Day 6 of our Python journey. 👋")
# 2. Calling the function
greet_user("Pythonista")
# 3. Function with parameters and a return value
def calculate_sum(num1, num2):
"""This function takes two numbers and returns their sum."""
total = num1 + num2
return total
# 4. Using the returned value
result = calculate_sum(15, 25)
print(f"The sum of 15 and 25 is: {result}")
# 5. Another call
greet_user("Beginner")
```
---
Output example:
```
Hello, Pythonista! Welcome to Day 6 of our Python journey. 👋
The sum of 15 and 25 is: 40
Hello, Beginner! Welcome to Day 6 of our Python journey. 👋
```
---
💡 **Your Challenge:**
Write a Python function called `get_fahrenheit` that takes a temperature in Celsius as a parameter and returns the temperature in Fahrenheit. (Formula: `F = C * 9/5 + 32`). Then, call your function with a sample Celsius value and print the result! Share your code snippets below! 👇
---
Hello, amazing learners! ✨ Today, we're diving into one of the most fundamental and powerful concepts in Python: **Functions**! Functions allow us to write reusable blocks of code, making our programs organized, efficient, and easier to understand. No more repetitive code! Let's unlock the magic of `def`! 🔑
---
```python
# 1. Defining a simple function
def greet_user(name):
"""This function greets the user by name."""
print(f"Hello, {name}! Welcome to Day 6 of our Python journey. 👋")
# 2. Calling the function
greet_user("Pythonista")
# 3. Function with parameters and a return value
def calculate_sum(num1, num2):
"""This function takes two numbers and returns their sum."""
total = num1 + num2
return total
# 4. Using the returned value
result = calculate_sum(15, 25)
print(f"The sum of 15 and 25 is: {result}")
# 5. Another call
greet_user("Beginner")
```
---
Output example:
```
Hello, Pythonista! Welcome to Day 6 of our Python journey. 👋
The sum of 15 and 25 is: 40
Hello, Beginner! Welcome to Day 6 of our Python journey. 👋
```
---
💡 **Your Challenge:**
Write a Python function called `get_fahrenheit` that takes a temperature in Celsius as a parameter and returns the temperature in Fahrenheit. (Formula: `F = C * 9/5 + 32`). Then, call your function with a sample Celsius value and print the result! Share your code snippets below! 👇
---
Which keyword is used to define a function in Python?
Anonymous Quiz
0%
function
100%
def
0%
func
0%
define
Here's your Telegram post and quiz question:
---
✨🐍 **Python Learning Series - Day 7: Lists and Tuples!** 🧠💡
Hello future Pythonistas! Today, we're diving into two fundamental data structures: **Lists** and **Tuples**. Both are ordered collections, but they have a crucial difference: lists are *mutable* (you can change them after creation), while tuples are *immutable* (they cannot be changed). Understanding this distinction is key to writing robust Python code! Let's explore. 👇
```python
# --- Lists: Mutable Ordered Collections ---
my_fruits = ["apple", "banana", "cherry"]
print(f"My fruit list: {my_fruits}")
# Lists are mutable: we can add, remove, or change elements
my_fruits.append("date")
print(f"After adding 'date': {my_fruits}")
my_fruits[0] = "apricot" # Change the first element
print(f"After changing 'apple' to 'apricot': {my_fruits}")
# --- Tuples: Immutable Ordered Collections ---
my_coordinates = (10.0, 20.5)
print(f"My coordinates tuple: {my_coordinates}")
# Tuples are immutable: once created, you cannot change their elements
# my_coordinates.append(30.0) # This would cause an error!
# my_coordinates[0] = 5.0 # This would also cause an error!
# You can access elements in both by index
print(f"Second fruit: {my_fruits[1]}")
print(f"X coordinate: {my_coordinates[0]}")
# You can even have a list of tuples or a tuple of lists!
user_profiles = [("Alice", 28), ("Bob", 34)]
print(f"User profiles (list of tuples): {user_profiles}")
```
Output example:
```
My fruit list: ['apple', 'banana', 'cherry']
After adding 'date': ['apple', 'banana', 'cherry', 'date']
After changing 'apple' to 'apricot': ['apricot', 'banana', 'cherry', 'date']
My coordinates tuple: (10.0, 20.5)
Second fruit: banana
X coordinate: 10.0
User profiles (list of tuples): [('Alice', 28), ('Bob', 34)]
```
🔥 **Small Challenge:**
Create a list called `my_favorite_movies` and add 3 movie titles. Then, create a tuple called `my_birth_date` with your birth year, month, and day. Try to add a fourth movie to your list and then try to change the month in your birth date tuple. What happens? Share your thoughts or code in the comments!
---
---
✨🐍 **Python Learning Series - Day 7: Lists and Tuples!** 🧠💡
Hello future Pythonistas! Today, we're diving into two fundamental data structures: **Lists** and **Tuples**. Both are ordered collections, but they have a crucial difference: lists are *mutable* (you can change them after creation), while tuples are *immutable* (they cannot be changed). Understanding this distinction is key to writing robust Python code! Let's explore. 👇
```python
# --- Lists: Mutable Ordered Collections ---
my_fruits = ["apple", "banana", "cherry"]
print(f"My fruit list: {my_fruits}")
# Lists are mutable: we can add, remove, or change elements
my_fruits.append("date")
print(f"After adding 'date': {my_fruits}")
my_fruits[0] = "apricot" # Change the first element
print(f"After changing 'apple' to 'apricot': {my_fruits}")
# --- Tuples: Immutable Ordered Collections ---
my_coordinates = (10.0, 20.5)
print(f"My coordinates tuple: {my_coordinates}")
# Tuples are immutable: once created, you cannot change their elements
# my_coordinates.append(30.0) # This would cause an error!
# my_coordinates[0] = 5.0 # This would also cause an error!
# You can access elements in both by index
print(f"Second fruit: {my_fruits[1]}")
print(f"X coordinate: {my_coordinates[0]}")
# You can even have a list of tuples or a tuple of lists!
user_profiles = [("Alice", 28), ("Bob", 34)]
print(f"User profiles (list of tuples): {user_profiles}")
```
Output example:
```
My fruit list: ['apple', 'banana', 'cherry']
After adding 'date': ['apple', 'banana', 'cherry', 'date']
After changing 'apple' to 'apricot': ['apricot', 'banana', 'cherry', 'date']
My coordinates tuple: (10.0, 20.5)
Second fruit: banana
X coordinate: 10.0
User profiles (list of tuples): [('Alice', 28), ('Bob', 34)]
```
🔥 **Small Challenge:**
Create a list called `my_favorite_movies` and add 3 movie titles. Then, create a tuple called `my_birth_date` with your birth year, month, and day. Try to add a fourth movie to your list and then try to change the month in your birth date tuple. What happens? Share your thoughts or code in the comments!
---
Which of the following Python data structures is immutable?
Anonymous Quiz
50%
list
0%
set
50%
tuple
0%
dictionary
Here's your Telegram post and quiz for Day 8:
---
👋 Hey Python Learners! 🚀 Welcome to Day 8 of our coding journey!
Today, we're unlocking the power of two incredibly versatile data structures: **Dictionaries** and **Sets**! 🧠 Dictionaries are your go-to for storing data in key-value pairs, perfect for mapping information like names to ages, or products to prices. Think of them as super-fast lookup tables! 📚
Then, we'll explore **Sets** – collections of unique items. They're fantastic for filtering out duplicates and performing mathematical set operations like unions and intersections. Get ready to organize your data like a pro! ✨
```python
# Day 8: Dictionaries & Sets
# --- Dictionaries ---
# Create a dictionary
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
print("Initial scores:", student_scores)
# Access a value by its key
print("Bob's score:", student_scores["Bob"])
# Add a new entry
student_scores["David"] = 95
print("Scores after adding David:", student_scores)
# Update an existing entry
student_scores["Alice"] = 88
print("Alice's updated score:", student_scores["Alice"])
# Loop through a dictionary's items
print("n--- Looping through scores ---")
for name, score in student_scores.items():
print(f"{name}: {score}")
# --- Sets ---
# Create a set (duplicates are automatically removed!)
my_numbers = {1, 2, 3, 2, 4, 1}
print("nUnique numbers in a set:", my_numbers)
# Add an element to a set
my_numbers.add(5)
print("Numbers after adding 5:", my_numbers)
# Set operations - Example: Union and Intersection
prime_numbers = {2, 3, 5, 7}
even_numbers = {2, 4, 6, 8}
# Union: Elements in either set
print("Primes OR Evens (Union):", prime_numbers.union(even_numbers))
# Intersection: Elements common to both sets
print("Primes AND Evens (Intersection):", prime_numbers.intersection(even_numbers))
```
Output example:
```
Initial scores: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
Bob's score: 92
Scores after adding David: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
Alice's updated score: 88
--- Looping through scores ---
Alice: 88
Bob: 92
Charlie: 78
David: 95
Unique numbers in a set: {1, 2, 3, 4}
Numbers after adding 5: {1, 2, 3, 4, 5}
Primes OR Evens (Union): {2, 3, 4, 5, 6, 7, 8}
Primes AND Evens (Intersection): {2}
```
### 💡 Small Challenge:
You have a list of cities visited by two friends:
`friend_a_cities = {"Paris", "London", "Rome", "Berlin"}`
`friend_b_cities = {"London", "Rome", "Madrid", "Barcelona"}`
1. Find all cities that *both* friends visited.
2. Find all unique cities visited by *at least one* friend.
3. Find cities visited by `friend_a` but *not* by `friend_b`.
(Hint: Use set operations! 😉)
---
---
👋 Hey Python Learners! 🚀 Welcome to Day 8 of our coding journey!
Today, we're unlocking the power of two incredibly versatile data structures: **Dictionaries** and **Sets**! 🧠 Dictionaries are your go-to for storing data in key-value pairs, perfect for mapping information like names to ages, or products to prices. Think of them as super-fast lookup tables! 📚
Then, we'll explore **Sets** – collections of unique items. They're fantastic for filtering out duplicates and performing mathematical set operations like unions and intersections. Get ready to organize your data like a pro! ✨
```python
# Day 8: Dictionaries & Sets
# --- Dictionaries ---
# Create a dictionary
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
print("Initial scores:", student_scores)
# Access a value by its key
print("Bob's score:", student_scores["Bob"])
# Add a new entry
student_scores["David"] = 95
print("Scores after adding David:", student_scores)
# Update an existing entry
student_scores["Alice"] = 88
print("Alice's updated score:", student_scores["Alice"])
# Loop through a dictionary's items
print("n--- Looping through scores ---")
for name, score in student_scores.items():
print(f"{name}: {score}")
# --- Sets ---
# Create a set (duplicates are automatically removed!)
my_numbers = {1, 2, 3, 2, 4, 1}
print("nUnique numbers in a set:", my_numbers)
# Add an element to a set
my_numbers.add(5)
print("Numbers after adding 5:", my_numbers)
# Set operations - Example: Union and Intersection
prime_numbers = {2, 3, 5, 7}
even_numbers = {2, 4, 6, 8}
# Union: Elements in either set
print("Primes OR Evens (Union):", prime_numbers.union(even_numbers))
# Intersection: Elements common to both sets
print("Primes AND Evens (Intersection):", prime_numbers.intersection(even_numbers))
```
Output example:
```
Initial scores: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
Bob's score: 92
Scores after adding David: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 95}
Alice's updated score: 88
--- Looping through scores ---
Alice: 88
Bob: 92
Charlie: 78
David: 95
Unique numbers in a set: {1, 2, 3, 4}
Numbers after adding 5: {1, 2, 3, 4, 5}
Primes OR Evens (Union): {2, 3, 4, 5, 6, 7, 8}
Primes AND Evens (Intersection): {2}
```
### 💡 Small Challenge:
You have a list of cities visited by two friends:
`friend_a_cities = {"Paris", "London", "Rome", "Berlin"}`
`friend_b_cities = {"London", "Rome", "Madrid", "Barcelona"}`
1. Find all cities that *both* friends visited.
2. Find all unique cities visited by *at least one* friend.
3. Find cities visited by `friend_a` but *not* by `friend_b`.
(Hint: Use set operations! 😉)
---
What is a primary characteristic of Python dictionary keys?
Anonymous Quiz
0%
They must be unique.
100%
They must be mutable.
0%
They must be integers.
0%
They can contain duplicate values.
Here's your Telegram post for Day 9: String Manipulation, along with the quiz question:
---
🌟 Day 9 of our Python journey is here, and it's all about **String Manipulation**! 🐍 Strings are fundamental for handling text data, from messages to file paths. Today, we'll dive into powerful techniques like *slicing*, *method calls* (think `replace()`!), and the incredibly useful *f-strings* for dynamic text formatting. Get ready to transform your text like a pro! ✨
```python
# Our main string for today!
message = "Hello, Python Learners! Welcome to Day 9 of our series."
print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")
# --- 1. String Slicing ---
# Extract a portion of the string
first_word = message[0:5] # From index 0 up to (but not including) 5
learning_topic = message[7:23] # "Python Learners!"
print(f"nFirst word (slice): '{first_word}'")
print(f"Learning topic (slice): '{learning_topic}'")
# --- 2. String Methods ---
# Using .replace() to swap words
modified_message = message.replace("Python Learners", "Coding Enthusiasts")
# Using .upper() and .lower()
uppercase_part = message[25:32].upper() # "WELCOME"
lowercase_part = message[0:5].lower() # "hello"
print(f"nMessage after replace(): '{modified_message}'")
print(f"Uppercase part: '{uppercase_part}'")
print(f"Lowercase part: '{lowercase_part}'")
# --- 3. F-strings (Formatted String Literals) ---
# Embed expressions directly inside string literals
day_number = 9
lesson_topic = "String Manipulation"
formatted_output = f"🚀 Today is Day {day_number}, and we're mastering {lesson_topic}!"
print(f"nUsing f-string for dynamic output: {formatted_output}")
```
Output example:
```
Original message: 'Hello, Python Learners! Welcome to Day 9 of our series.'
Length of message: 57
First word (slice): 'Hello'
Learning topic (slice): 'Python Learners!'
Message after replace(): 'Hello, Coding Enthusiasts! Welcome to Day 9 of our series.'
Uppercase part: 'WELCOME'
Lowercase part: 'hello'
Using f-string for dynamic output: 🚀 Today is Day 9, and we're mastering String Manipulation!
```
🔥 **CHALLENGE:** Can you extract the phrase "our series" from the `message` variable using slicing, and then print it backwards using slicing (e.g., `series ruo`)? Share your solution! 👇
---
---
🌟 Day 9 of our Python journey is here, and it's all about **String Manipulation**! 🐍 Strings are fundamental for handling text data, from messages to file paths. Today, we'll dive into powerful techniques like *slicing*, *method calls* (think `replace()`!), and the incredibly useful *f-strings* for dynamic text formatting. Get ready to transform your text like a pro! ✨
```python
# Our main string for today!
message = "Hello, Python Learners! Welcome to Day 9 of our series."
print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")
# --- 1. String Slicing ---
# Extract a portion of the string
first_word = message[0:5] # From index 0 up to (but not including) 5
learning_topic = message[7:23] # "Python Learners!"
print(f"nFirst word (slice): '{first_word}'")
print(f"Learning topic (slice): '{learning_topic}'")
# --- 2. String Methods ---
# Using .replace() to swap words
modified_message = message.replace("Python Learners", "Coding Enthusiasts")
# Using .upper() and .lower()
uppercase_part = message[25:32].upper() # "WELCOME"
lowercase_part = message[0:5].lower() # "hello"
print(f"nMessage after replace(): '{modified_message}'")
print(f"Uppercase part: '{uppercase_part}'")
print(f"Lowercase part: '{lowercase_part}'")
# --- 3. F-strings (Formatted String Literals) ---
# Embed expressions directly inside string literals
day_number = 9
lesson_topic = "String Manipulation"
formatted_output = f"🚀 Today is Day {day_number}, and we're mastering {lesson_topic}!"
print(f"nUsing f-string for dynamic output: {formatted_output}")
```
Output example:
```
Original message: 'Hello, Python Learners! Welcome to Day 9 of our series.'
Length of message: 57
First word (slice): 'Hello'
Learning topic (slice): 'Python Learners!'
Message after replace(): 'Hello, Coding Enthusiasts! Welcome to Day 9 of our series.'
Uppercase part: 'WELCOME'
Lowercase part: 'hello'
Using f-string for dynamic output: 🚀 Today is Day 9, and we're mastering String Manipulation!
```
🔥 **CHALLENGE:** Can you extract the phrase "our series" from the `message` variable using slicing, and then print it backwards using slicing (e.g., `series ruo`)? Share your solution! 👇
---
What will be the output of the following Python code?
```python
text = " Hello World! " result = text.strip().lower().replace("world", "python") print(result) ```
```python
text = " Hello World! " result = text.strip().lower().replace("world", "python") print(result) ```
Anonymous Quiz
100%
hello python!
0%
Hello Python!
0%
hello python!
0%
hello world!
Here's your Telegram post and quiz!
---
🎉 **Python Learning Series - Day 10: File I/O (Input/Output)** 🎉
Time to level up! 🚀 On Day 10, we're diving into *File I/O* in Python. No more just printing to the console – now you can store and retrieve data persistently! We'll learn how to `open`, `read`, `write`, and manage files safely using the `with` statement. Get ready to make your programs remember! 💾📝
```python
# --- Day 10: File I/O ---
# 1. Writing to a file (mode 'w' - write, overwrites existing file)
# The 'with' statement ensures the file is automatically closed.
with open("my_notes.txt", "w") as file:
file.write("Hello from Day 10!n")
file.write("Python file I/O is fun. 😊n")
file.write("This is a new line.n")
print("Data written to my_notes.txt")
# 2. Reading from a file (mode 'r' - read)
print("n--- Reading file content ---")
with open("my_notes.txt", "r") as file:
content = file.read() # Reads the entire file content
print(content)
# 3. Appending to a file (mode 'a' - append, adds to the end)
with open("my_notes.txt", "a") as file:
file.write("This line was appended later. ✨n")
print("Data appended to my_notes.txt")
# 4. Reading again to see the appended content
print("n--- Reading file content after append ---")
with open("my_notes.txt", "r") as file:
print(file.read())
```
Output example:
```
Data written to my_notes.txt
--- Reading file content ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
Data appended to my_notes.txt
--- Reading file content after append ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
This line was appended later. ✨
```
---
💡 **Small Challenge:**
Can you write a Python script that asks the user for 3 different shopping list items and then saves each item to a file named `shopping_list.txt`, with each item on a new line? (Hint: Use a loop and input()!)
---
---
🎉 **Python Learning Series - Day 10: File I/O (Input/Output)** 🎉
Time to level up! 🚀 On Day 10, we're diving into *File I/O* in Python. No more just printing to the console – now you can store and retrieve data persistently! We'll learn how to `open`, `read`, `write`, and manage files safely using the `with` statement. Get ready to make your programs remember! 💾📝
```python
# --- Day 10: File I/O ---
# 1. Writing to a file (mode 'w' - write, overwrites existing file)
# The 'with' statement ensures the file is automatically closed.
with open("my_notes.txt", "w") as file:
file.write("Hello from Day 10!n")
file.write("Python file I/O is fun. 😊n")
file.write("This is a new line.n")
print("Data written to my_notes.txt")
# 2. Reading from a file (mode 'r' - read)
print("n--- Reading file content ---")
with open("my_notes.txt", "r") as file:
content = file.read() # Reads the entire file content
print(content)
# 3. Appending to a file (mode 'a' - append, adds to the end)
with open("my_notes.txt", "a") as file:
file.write("This line was appended later. ✨n")
print("Data appended to my_notes.txt")
# 4. Reading again to see the appended content
print("n--- Reading file content after append ---")
with open("my_notes.txt", "r") as file:
print(file.read())
```
Output example:
```
Data written to my_notes.txt
--- Reading file content ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
Data appended to my_notes.txt
--- Reading file content after append ---
Hello from Day 10!
Python file I/O is fun. 😊
This is a new line.
This line was appended later. ✨
```
---
💡 **Small Challenge:**
Can you write a Python script that asks the user for 3 different shopping list items and then saves each item to a file named `shopping_list.txt`, with each item on a new line? (Hint: Use a loop and input()!)
---
What is the primary benefit of using the `with open(...) as file:` statement when working with files in Python?
Anonymous Quiz
0%
A. It automatically creates the file if it doesn't exist, regardless of the mode.
0%
B. It ensures the file is automatically closed, even if errors occur.
0%
C. It allows writing to binary files without explicit encoding.
100%
D. It makes file operations significantly faster.
Hey Python Learners! 👋 Ready to make your code bulletproof? 🛡️ Today is Day 11, and we're diving into *Error Handling* with `try` and `except`! 🐛 No one likes a crashing program. Learning to anticipate and gracefully handle errors means your scripts can recover instead of stopping dead in their tracks. Let's write robust code that users will love! ✨
```python
print("--- Python Error Handling ---")
def calculate_division(numerator, denominator):
try:
# Code that might raise an exception
result = float(numerator) / float(denominator)
except ZeroDivisionError:
# Handles specific error: division by zero
print("🚫 Error: Cannot divide by zero!")
return None
except ValueError:
# Handles specific error: non-numeric input for float conversion
print("🔢 Error: Please enter valid numbers for calculation.")
return None
except Exception as e:
# Catches any other unexpected errors
print(f"❌ An unexpected error occurred: {e}")
return None
else:
# Code runs ONLY if no exceptions occurred in the try block
print(f"✅ Division successful! Result: {result}")
return result
finally:
# Code runs ALWAYS, regardless of success or failure
print("➡️ Division attempt concluded.")
# --- Test Cases ---
print("n--- Test 1: Valid Division ---")
calculate_division(10, 2)
print("n--- Test 2: Division by Zero ---")
calculate_division(10, 0)
print("n--- Test 3: Invalid Input (string) ---")
calculate_division("ten", 2)
print("n--- Test 4: Another Valid Division ---")
calculate_division(25, 4)
```
Output example:
```
--- Python Error Handling ---
--- Test 1: Valid Division ---
✅ Division successful! Result: 5.0
➡️ Division attempt concluded.
--- Test 2: Division by Zero ---
🚫 Error: Cannot divide by zero!
➡️ Division attempt concluded.
--- Test 3: Invalid Input (string) ---
🔢 Error: Please enter valid numbers for calculation.
➡️ Division attempt concluded.
--- Test 4: Another Valid Division ---
✅ Division successful! Result: 6.25
➡️ Division attempt concluded.
```
💡 **Challenge Time!**
Modify the `calculate_division` function to also handle a `TypeError` specifically if you try to pass an object type that cannot be converted to `float` (e.g., `calculate_division([1,2], 2)`). Where would you place this new `except` block? 🤔 Share your thoughts or code snippets!
```python
print("--- Python Error Handling ---")
def calculate_division(numerator, denominator):
try:
# Code that might raise an exception
result = float(numerator) / float(denominator)
except ZeroDivisionError:
# Handles specific error: division by zero
print("🚫 Error: Cannot divide by zero!")
return None
except ValueError:
# Handles specific error: non-numeric input for float conversion
print("🔢 Error: Please enter valid numbers for calculation.")
return None
except Exception as e:
# Catches any other unexpected errors
print(f"❌ An unexpected error occurred: {e}")
return None
else:
# Code runs ONLY if no exceptions occurred in the try block
print(f"✅ Division successful! Result: {result}")
return result
finally:
# Code runs ALWAYS, regardless of success or failure
print("➡️ Division attempt concluded.")
# --- Test Cases ---
print("n--- Test 1: Valid Division ---")
calculate_division(10, 2)
print("n--- Test 2: Division by Zero ---")
calculate_division(10, 0)
print("n--- Test 3: Invalid Input (string) ---")
calculate_division("ten", 2)
print("n--- Test 4: Another Valid Division ---")
calculate_division(25, 4)
```
Output example:
```
--- Python Error Handling ---
--- Test 1: Valid Division ---
✅ Division successful! Result: 5.0
➡️ Division attempt concluded.
--- Test 2: Division by Zero ---
🚫 Error: Cannot divide by zero!
➡️ Division attempt concluded.
--- Test 3: Invalid Input (string) ---
🔢 Error: Please enter valid numbers for calculation.
➡️ Division attempt concluded.
--- Test 4: Another Valid Division ---
✅ Division successful! Result: 6.25
➡️ Division attempt concluded.
```
💡 **Challenge Time!**
Modify the `calculate_division` function to also handle a `TypeError` specifically if you try to pass an object type that cannot be converted to `float` (e.g., `calculate_division([1,2], 2)`). Where would you place this new `except` block? 🤔 Share your thoughts or code snippets!
What is the primary purpose of the `else` block in a `try-except-else-finally` construct in Python?
Anonymous Quiz
100%
A. To execute code only if an exception occurred in the `try` block.
0%
B. To execute code regardless of whether an exception occurred or not.
0%
C. To define the code that might raise an exception.
0%
D. To execute code only if no exceptions occurred in the `try` block.