Here's your Telegram post for Day 5 of the Python learning series!
---
Hello Python Learners! 👋 Day 5 is here, and we're diving into one of programming's superpowers: *loops*! 🚀 Loops allow your code to repeat actions efficiently, saving you tons of time and effort. Whether you know exactly how many times you need to repeat something (`for` loop) or you need to keep going until a condition is met (`while` loop), loops are your best friends for automation. Let's make our programs dynamic! ✨
```python
# Day 5: Loops (for and while)
# --- The 'for' Loop ---
# Used for iterating over a sequence (like a list, tuple, dictionary, set, or string)
# or other iterable objects. Great when you know how many times you want to loop.
print("--- For Loop Example: Iterating over a list ---")
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I love {fruit}!")
print("n--- For Loop Example: Using range() ---")
# range(start, stop, step) - stop is exclusive
for i in range(3): # This will give 0, 1, 2
print(f"Counting with for: {i}")
# --- The 'while' Loop ---
# Executes a block of code as long as a specified condition is true.
# Be careful not to create an infinite loop!
print("n--- While Loop Example ---")
countdown = 3
while countdown > 0:
print(f"Countdown: {countdown}...")
countdown -= 1 # Decrement the counter to eventually make the condition false
print("Lift off! 🚀")
```
Output example:
```
--- For Loop Example: Iterating over a list ---
I love apple!
I love banana!
I love cherry!
I love date!
--- For Loop Example: Using range() ---
Counting with for: 0
Counting with for: 1
Counting with for: 2
--- While Loop Example ---
Countdown: 3...
Countdown: 2...
Countdown: 1...
Lift off! 🚀
```
**Small Challenge:** 💪
Write a `for` loop that prints all even numbers from 2 to 10 (inclusive). Share your code in the comments! 👇
---
---
Hello Python Learners! 👋 Day 5 is here, and we're diving into one of programming's superpowers: *loops*! 🚀 Loops allow your code to repeat actions efficiently, saving you tons of time and effort. Whether you know exactly how many times you need to repeat something (`for` loop) or you need to keep going until a condition is met (`while` loop), loops are your best friends for automation. Let's make our programs dynamic! ✨
```python
# Day 5: Loops (for and while)
# --- The 'for' Loop ---
# Used for iterating over a sequence (like a list, tuple, dictionary, set, or string)
# or other iterable objects. Great when you know how many times you want to loop.
print("--- For Loop Example: Iterating over a list ---")
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I love {fruit}!")
print("n--- For Loop Example: Using range() ---")
# range(start, stop, step) - stop is exclusive
for i in range(3): # This will give 0, 1, 2
print(f"Counting with for: {i}")
# --- The 'while' Loop ---
# Executes a block of code as long as a specified condition is true.
# Be careful not to create an infinite loop!
print("n--- While Loop Example ---")
countdown = 3
while countdown > 0:
print(f"Countdown: {countdown}...")
countdown -= 1 # Decrement the counter to eventually make the condition false
print("Lift off! 🚀")
```
Output example:
```
--- For Loop Example: Iterating over a list ---
I love apple!
I love banana!
I love cherry!
I love date!
--- For Loop Example: Using range() ---
Counting with for: 0
Counting with for: 1
Counting with for: 2
--- While Loop Example ---
Countdown: 3...
Countdown: 2...
Countdown: 1...
Lift off! 🚀
```
**Small Challenge:** 💪
Write a `for` loop that prints all even numbers from 2 to 10 (inclusive). Share your code in the comments! 👇
---
What will be the output of the following Python code?
```python count = 0 while count < 4: print(count * 2) count += 1 ```
```python count = 0 while count < 4: print(count * 2) count += 1 ```
Anonymous Quiz
0%
0 2 4 6
100%
0 1 2 3
0%
2 4 6 8
0%
0 2 4 6 8
🎉 Hey Python learners! 🚀 Ready for Day 6? Today, we're diving into the superpower of Python: *functions*! 🧱 Functions are reusable blocks of code that perform a specific task, helping you write cleaner, more organized, and less repetitive programs. Think of them as mini-programs within your main program! Let's unlock their magic! ✨
Functions are defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Parameters go inside the parentheses.
```python
# Defining a simple function to greet someone
def greet(name):
"""This function takes a name and prints a personalized greeting."""
print(f"👋 Hello, {name}! Welcome to Day 6 of Python!")
# Defining a function that performs a calculation and returns a value
def add_numbers(a, b):
"""This function takes two numbers and returns their sum."""
return a + b
# --- Calling our functions ---
# Call the greet function with different names
greet("Pythonista")
greet("Learner")
# Call the add_numbers function and store its returned value
sum_result = add_numbers(10, 5)
print(f"The sum of 10 and 5 is: {sum_result}")
another_sum = add_numbers(2.5, 7.5)
print(f"The sum of 2.5 and 7.5 is: {another_sum}")
```
Output example:
```
👋 Hello, Pythonista! Welcome to Day 6 of Python!
👋 Hello, Learner! Welcome to Day 6 of Python!
The sum of 10 and 5 is: 15
The sum of 2.5 and 7.5 is: 10.0
```
### Small Challenge:
Your turn! 🚀 Create a function called `multiply(x, y)` that takes two numbers as arguments and returns their product. Then call your `multiply` function with any two numbers and print the result!
---
Functions are defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Parameters go inside the parentheses.
```python
# Defining a simple function to greet someone
def greet(name):
"""This function takes a name and prints a personalized greeting."""
print(f"👋 Hello, {name}! Welcome to Day 6 of Python!")
# Defining a function that performs a calculation and returns a value
def add_numbers(a, b):
"""This function takes two numbers and returns their sum."""
return a + b
# --- Calling our functions ---
# Call the greet function with different names
greet("Pythonista")
greet("Learner")
# Call the add_numbers function and store its returned value
sum_result = add_numbers(10, 5)
print(f"The sum of 10 and 5 is: {sum_result}")
another_sum = add_numbers(2.5, 7.5)
print(f"The sum of 2.5 and 7.5 is: {another_sum}")
```
Output example:
```
👋 Hello, Pythonista! Welcome to Day 6 of Python!
👋 Hello, Learner! Welcome to Day 6 of Python!
The sum of 10 and 5 is: 15
The sum of 2.5 and 7.5 is: 10.0
```
### Small Challenge:
Your turn! 🚀 Create a function called `multiply(x, y)` that takes two numbers as arguments and returns their product. Then call your `multiply` function with any two numbers and print the result!
---
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!
---
🐍 Python Learning Series - Day 7! ✨ Today, we dive into two fundamental data structures: *Lists* and *Tuples*! 📚 You'll learn how to store collections of items, access them, and understand the key differences between these versatile types. Get ready to organize your data like a pro! 🚀
```python
# Day 7: Lists and Tuples - Organizing Collections
# --- Lists (Mutable, ordered collection) ---
my_list = [1, 2, 3, "apple", True]
print(f"Original list: {my_list}")
# Accessing elements
print(f"First element of list: {my_list[0]}")
print(f"Last element of list: {my_list[-1]}")
# Modifying a list (Lists are mutable!)
my_list.append("banana")
print(f"List after append: {my_list}")
my_list[1] = 20 # Change an element by index
print(f"List after modification: {my_list}")
my_list.remove("apple")
print(f"List after remove: {my_list}")
# Slicing a list
print(f"List slice (index 1 to 3): {my_list[1:4]}")
# --- Tuples (Immutable, ordered collection) ---
my_tuple = (10, 20, "orange", False)
print(f"nOriginal tuple: {my_tuple}")
# Accessing elements (similar to lists)
print(f"First element of tuple: {my_tuple[0]}")
print(f"Last element of tuple: {my_tuple[-1]}")
# Tuples are IMMUTABLE - cannot change after creation!
# Uncommenting the line below would raise a TypeError:
# my_tuple[0] = 100
# print(f"Trying to modify tuple: {my_tuple}") # This will fail!
# Concatenating tuples (creates a NEW tuple)
new_tuple = my_tuple + (True, 50)
print(f"Concatenated tuple (new tuple created): {new_tuple}")
# Checking types
print(f"Type of my_list: {type(my_list)}")
print(f"Type of my_tuple: {type(my_tuple)}")
```
Output example:
```
Original list: [1, 2, 3, 'apple', True]
First element of list: 1
Last element of list: True
List after append: [1, 2, 3, 'apple', True, 'banana']
List after modification: [1, 20, 3, 'apple', True, 'banana']
List after remove: [1, 20, 3, True, 'banana']
List slice (index 1 to 3): [20, 3, True]
Original tuple: (10, 20, 'orange', False)
First element of tuple: 10
Last element of tuple: False
Concatenated tuple (new tuple created): (10, 20, 'orange', False, True, 50)
Type of my_list: <class 'list'>
Type of my_tuple: <class 'tuple'>
```
Small challenge:
Challenge: Create a list of your 3 favorite colors. Now, create a tuple containing the same colors but in a different order. Try to add a 4th color to your *tuple* and observe what happens! 🎨🖌️
---
Here's a quiz question related to today's lesson:
---
🐍 Python Learning Series - Day 7! ✨ Today, we dive into two fundamental data structures: *Lists* and *Tuples*! 📚 You'll learn how to store collections of items, access them, and understand the key differences between these versatile types. Get ready to organize your data like a pro! 🚀
```python
# Day 7: Lists and Tuples - Organizing Collections
# --- Lists (Mutable, ordered collection) ---
my_list = [1, 2, 3, "apple", True]
print(f"Original list: {my_list}")
# Accessing elements
print(f"First element of list: {my_list[0]}")
print(f"Last element of list: {my_list[-1]}")
# Modifying a list (Lists are mutable!)
my_list.append("banana")
print(f"List after append: {my_list}")
my_list[1] = 20 # Change an element by index
print(f"List after modification: {my_list}")
my_list.remove("apple")
print(f"List after remove: {my_list}")
# Slicing a list
print(f"List slice (index 1 to 3): {my_list[1:4]}")
# --- Tuples (Immutable, ordered collection) ---
my_tuple = (10, 20, "orange", False)
print(f"nOriginal tuple: {my_tuple}")
# Accessing elements (similar to lists)
print(f"First element of tuple: {my_tuple[0]}")
print(f"Last element of tuple: {my_tuple[-1]}")
# Tuples are IMMUTABLE - cannot change after creation!
# Uncommenting the line below would raise a TypeError:
# my_tuple[0] = 100
# print(f"Trying to modify tuple: {my_tuple}") # This will fail!
# Concatenating tuples (creates a NEW tuple)
new_tuple = my_tuple + (True, 50)
print(f"Concatenated tuple (new tuple created): {new_tuple}")
# Checking types
print(f"Type of my_list: {type(my_list)}")
print(f"Type of my_tuple: {type(my_tuple)}")
```
Output example:
```
Original list: [1, 2, 3, 'apple', True]
First element of list: 1
Last element of list: True
List after append: [1, 2, 3, 'apple', True, 'banana']
List after modification: [1, 20, 3, 'apple', True, 'banana']
List after remove: [1, 20, 3, True, 'banana']
List slice (index 1 to 3): [20, 3, True]
Original tuple: (10, 20, 'orange', False)
First element of tuple: 10
Last element of tuple: False
Concatenated tuple (new tuple created): (10, 20, 'orange', False, True, 50)
Type of my_list: <class 'list'>
Type of my_tuple: <class 'tuple'>
```
Small challenge:
Challenge: Create a list of your 3 favorite colors. Now, create a tuple containing the same colors but in a different order. Try to add a 4th color to your *tuple* and observe what happens! 🎨🖌️
---
Here's a quiz question related to today's lesson:
Which of the following statements about Python lists and tuples is true?
Anonymous Quiz
100%
A) Lists are immutable, while tuples are mutable.
0%
B) Both lists and tuples are mutable.
0%
C) Lists are mutable, while tuples are immutable.
0%
D) Both lists and tuples are immutable.
Which of the following is TRUE about Python dictionaries and sets?
Anonymous Quiz
0%
Dictionary keys must be unique and immutable; set elements must be unique and immutable.
100%
Dictionary keys must be unique but can be mutable; set elements must be unique but can be mutable.
0%
Dictionary keys can be duplicated; set elements must be unique and immutable.
0%
Both dictionary keys and set elements can be duplicated.
🚀 Day 9 of our Python journey is here, and it's all about mastering **String Manipulation**! 🐍 Strings are fundamental in Python, and knowing how to effectively work with them is crucial for everything from data processing to user interfaces. Today, we'll dive into powerful methods to slice, dice, transform, and search text. Get ready to make your strings dance with `len()`, `split()`, `replace()`, and more! Let's code! ✨
```python
# Day 9: String Manipulation - Making text work for you!
message = " Hello Python Learners! Keep Coding! "
name = "Alice"
print("--- String Basics ---")
# 1. Length of a string
print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")
# 2. String concatenation (joining strings)
greeting = "Good morning, " + name + "!"
print(f"Concatenation: {greeting}")
# 3. String slicing (extracting parts)
first_word = message[2:7] # From index 2 up to (but not including) 7
print(f"Slicing (first word 'Hello'): '{first_word}'")
last_part = message[20:] # From index 20 to the end
print(f"Slicing (from index 20): '{last_part}'")
reversed_message = message[::-1] # A common trick for reversing
print(f"Reversed message: '{reversed_message}'")
print("n--- Transformation Methods ---")
# 4. Uppercase and Lowercase
upper_case = message.upper()
print(f"Uppercase: '{upper_case}'")
lower_case = message.lower()
print(f"Lowercase: '{lower_case}'")
# 5. Replacing parts of a string
modified_message = message.replace("Coding", "Learning")
print(f"Replace 'Coding' with 'Learning': '{modified_message}'")
# 6. Splitting a string into a list of words/parts
sentence = "Python is super fun"
words = sentence.split(" ") # Split by space
print(f"Split by space: {words}")
# 7. Joining a list of strings into a single string
joined_words = "-".join(["Python", "is", "awesome"])
print(f"Join with hyphen: '{joined_words}'")
print("n--- Search & Clean-up Methods ---")
# 8. Finding a substring (returns index or -1 if not found)
find_index = message.find("Python")
print(f"Find 'Python' at index: {find_index}")
not_found = message.find("Java")
print(f"Find 'Java' (not found): {not_found}") # -1 means not found
# 9. Stripping whitespace from start/end
stripped_message = message.strip()
print(f"Stripped whitespace: '{stripped_message}'")
```
Output example:
```
--- String Basics ---
Original message: ' Hello Python Learners! Keep Coding! '
Length of message: 39
Concatenation: Good morning, Alice!
Slicing (first word 'Hello'): 'Hello'
Slicing (from index 20): 'Keep Coding! '
Reversed message: ' !gnidoC peeK !srenraeL nohtyP olleH '
--- Transformation Methods ---
Uppercase: ' HELLO PYTHON LEARNERS! KEEP CODING! '
Lowercase: ' hello python learners! keep coding! '
Replace 'Coding' with 'Learning': ' Hello Python Learners! Keep Learning! '
Split by space: ['Python', 'is', 'super', 'fun']
Join with hyphen: 'Python-is-awesome'
--- Search & Clean-up Methods ---
Find 'Python' at index: 9
Find 'Java' (not found): -1
Stripped whitespace: 'Hello Python Learners! Keep Coding!'
```
💡 **Your Challenge:**
Create a string with a messy email address like ` " My.Email@EXAMPLE.com " `.
Then, use string methods to:
1. Remove all leading/trailing whitespace.
2. Convert the entire email to lowercase.
3. Replace ".com" with ".org".
Print the final cleaned and modified email! 📧
---
```python
# Day 9: String Manipulation - Making text work for you!
message = " Hello Python Learners! Keep Coding! "
name = "Alice"
print("--- String Basics ---")
# 1. Length of a string
print(f"Original message: '{message}'")
print(f"Length of message: {len(message)}")
# 2. String concatenation (joining strings)
greeting = "Good morning, " + name + "!"
print(f"Concatenation: {greeting}")
# 3. String slicing (extracting parts)
first_word = message[2:7] # From index 2 up to (but not including) 7
print(f"Slicing (first word 'Hello'): '{first_word}'")
last_part = message[20:] # From index 20 to the end
print(f"Slicing (from index 20): '{last_part}'")
reversed_message = message[::-1] # A common trick for reversing
print(f"Reversed message: '{reversed_message}'")
print("n--- Transformation Methods ---")
# 4. Uppercase and Lowercase
upper_case = message.upper()
print(f"Uppercase: '{upper_case}'")
lower_case = message.lower()
print(f"Lowercase: '{lower_case}'")
# 5. Replacing parts of a string
modified_message = message.replace("Coding", "Learning")
print(f"Replace 'Coding' with 'Learning': '{modified_message}'")
# 6. Splitting a string into a list of words/parts
sentence = "Python is super fun"
words = sentence.split(" ") # Split by space
print(f"Split by space: {words}")
# 7. Joining a list of strings into a single string
joined_words = "-".join(["Python", "is", "awesome"])
print(f"Join with hyphen: '{joined_words}'")
print("n--- Search & Clean-up Methods ---")
# 8. Finding a substring (returns index or -1 if not found)
find_index = message.find("Python")
print(f"Find 'Python' at index: {find_index}")
not_found = message.find("Java")
print(f"Find 'Java' (not found): {not_found}") # -1 means not found
# 9. Stripping whitespace from start/end
stripped_message = message.strip()
print(f"Stripped whitespace: '{stripped_message}'")
```
Output example:
```
--- String Basics ---
Original message: ' Hello Python Learners! Keep Coding! '
Length of message: 39
Concatenation: Good morning, Alice!
Slicing (first word 'Hello'): 'Hello'
Slicing (from index 20): 'Keep Coding! '
Reversed message: ' !gnidoC peeK !srenraeL nohtyP olleH '
--- Transformation Methods ---
Uppercase: ' HELLO PYTHON LEARNERS! KEEP CODING! '
Lowercase: ' hello python learners! keep coding! '
Replace 'Coding' with 'Learning': ' Hello Python Learners! Keep Learning! '
Split by space: ['Python', 'is', 'super', 'fun']
Join with hyphen: 'Python-is-awesome'
--- Search & Clean-up Methods ---
Find 'Python' at index: 9
Find 'Java' (not found): -1
Stripped whitespace: 'Hello Python Learners! Keep Coding!'
```
💡 **Your Challenge:**
Create a string with a messy email address like ` " My.Email@EXAMPLE.com " `.
Then, use string methods to:
1. Remove all leading/trailing whitespace.
2. Convert the entire email to lowercase.
3. Replace ".com" with ".org".
Print the final cleaned and modified email! 📧
---
What will be the output of the following Python code?
text = "apple,banana,cherry" parts = text.split(',') result = "-".join(parts) print(result)
text = "apple,banana,cherry" parts = text.split(',') result = "-".join(parts) print(result)
Anonymous Quiz
0%
['apple', 'banana', 'cherry']
0%
apple-banana-cherry
0%
apple,banana,cherry
0%
apple,banana,cherry-
Hello Python learners! 👋 On Day 10, we're diving into *File I/O* (Input/Output)! 📂 This essential skill allows your programs to read data from files and write results back to them, making your data persistent. No more losing info when your script ends! We'll cover opening files, basic modes (`'r'` for read, `'w'` for write), and the golden rule: using `with open(...)` for safe file handling. Let's make our Python scripts remember things! ✨
```python
# Define a filename
my_file = "learning_log.txt"
# --- Part 1: Writing to a file ---
print(f"Creating and writing to '{my_file}'...")
with open(my_file, "w") as f: # 'w' mode (write) will create or overwrite
f.write("Day 10: File I/O session.n")
f.write("We are learning to persist data!n")
f.write("This line was added using Python's write() method. 👋n")
print(f"Successfully wrote data to '{my_file}'.")
# --- Part 2: Reading from a file ---
print(f"nReading content from '{my_file}'...")
with open(my_file, "r") as f: # 'r' mode (read)
file_content = f.read() # Reads the entire file content
print("--- File Content Start ---")
print(file_content)
print("--- File Content End ---")
print(f"Successfully read data from '{my_file}'.")
```
Output example:
```
Creating and writing to 'learning_log.txt'...
Successfully wrote data to 'learning_log.txt'.
Reading content from 'learning_log.txt'...
--- File Content Start ---
Day 10: File I/O session.
We are learning to persist data!
This line was added using Python's write() method. 👋
--- File Content End ---
Successfully read data from 'learning_log.txt'.
```
Challenge Time! 🚀 Modify the code to *append* a new line of text to `learning_log.txt` without overwriting the existing content. Then, read the *entire* file again to see the updated content! (Hint: Think about file modes!)
---
```python
# Define a filename
my_file = "learning_log.txt"
# --- Part 1: Writing to a file ---
print(f"Creating and writing to '{my_file}'...")
with open(my_file, "w") as f: # 'w' mode (write) will create or overwrite
f.write("Day 10: File I/O session.n")
f.write("We are learning to persist data!n")
f.write("This line was added using Python's write() method. 👋n")
print(f"Successfully wrote data to '{my_file}'.")
# --- Part 2: Reading from a file ---
print(f"nReading content from '{my_file}'...")
with open(my_file, "r") as f: # 'r' mode (read)
file_content = f.read() # Reads the entire file content
print("--- File Content Start ---")
print(file_content)
print("--- File Content End ---")
print(f"Successfully read data from '{my_file}'.")
```
Output example:
```
Creating and writing to 'learning_log.txt'...
Successfully wrote data to 'learning_log.txt'.
Reading content from 'learning_log.txt'...
--- File Content Start ---
Day 10: File I/O session.
We are learning to persist data!
This line was added using Python's write() method. 👋
--- File Content End ---
Successfully read data from 'learning_log.txt'.
```
Challenge Time! 🚀 Modify the code to *append* a new line of text to `learning_log.txt` without overwriting the existing content. Then, read the *entire* file again to see the updated content! (Hint: Think about file modes!)
---
Which file mode should you use to add new content to an existing file without deleting its original content?
Anonymous Quiz
0%
'w'
0%
'r'
0%
'a'
0%
'x'
Alright, Python explorers! 🚀 Get ready to build more robust and user-friendly applications!
---
### **Day 11: Error Handling (try, except)**
Ever had your Python script crash unexpectedly? 🐛 Today, we tackle how to gracefully handle those hiccups! With `try` and `except` blocks, you can anticipate potential errors, prevent your program from stopping abruptly, and provide meaningful feedback to users. It's like giving your code a safety net! 🛠️ Let's dive into making your programs more resilient!
```python
print("--- Day 11: Error Handling (try, except) ---")
try:
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")
num1 = int(num1_str) # This might raise ValueError
num2 = int(num2_str) # This might raise ValueError
result = num1 / num2 # This might raise ZeroDivisionError
print(f"The result of {num1} / {num2} is: {result}")
except ValueError:
# Catches errors when conversion to int fails (e.g., input is 'abc')
print("Oops! 🛑 Invalid input. Please enter whole numbers only.")
except ZeroDivisionError:
# Catches errors when attempting to divide by zero
print("Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.")
except Exception as e:
# A generic catch-all for any other unexpected errors
print(f"An unexpected error occurred: {e}")
finally:
# This block always executes, regardless of whether an exception occurred or not
print("Error handling check complete. ✨")
print("Program continues its execution. 🎉")
```
Output example (if you enter `10` and `0`):
```
--- Day 11: Error Handling (try, except) ---
Enter the first number: 10
Enter the second number: 0
Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.
Error handling check complete. ✨
Program continues its execution. 🎉
```
---
### **Small Challenge:**
Can you modify the code above to keep asking the user for input (in a loop) until two *valid* numbers are entered and a successful division operation can be performed? 🤔 (Hint: Think `while` loop!)
---
---
### **Day 11: Error Handling (try, except)**
Ever had your Python script crash unexpectedly? 🐛 Today, we tackle how to gracefully handle those hiccups! With `try` and `except` blocks, you can anticipate potential errors, prevent your program from stopping abruptly, and provide meaningful feedback to users. It's like giving your code a safety net! 🛠️ Let's dive into making your programs more resilient!
```python
print("--- Day 11: Error Handling (try, except) ---")
try:
num1_str = input("Enter the first number: ")
num2_str = input("Enter the second number: ")
num1 = int(num1_str) # This might raise ValueError
num2 = int(num2_str) # This might raise ValueError
result = num1 / num2 # This might raise ZeroDivisionError
print(f"The result of {num1} / {num2} is: {result}")
except ValueError:
# Catches errors when conversion to int fails (e.g., input is 'abc')
print("Oops! 🛑 Invalid input. Please enter whole numbers only.")
except ZeroDivisionError:
# Catches errors when attempting to divide by zero
print("Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.")
except Exception as e:
# A generic catch-all for any other unexpected errors
print(f"An unexpected error occurred: {e}")
finally:
# This block always executes, regardless of whether an exception occurred or not
print("Error handling check complete. ✨")
print("Program continues its execution. 🎉")
```
Output example (if you enter `10` and `0`):
```
--- Day 11: Error Handling (try, except) ---
Enter the first number: 10
Enter the second number: 0
Error! 🚫 Cannot divide by zero. Please enter a non-zero second number.
Error handling check complete. ✨
Program continues its execution. 🎉
```
---
### **Small Challenge:**
Can you modify the code above to keep asking the user for input (in a loop) until two *valid* numbers are entered and a successful division operation can be performed? 🤔 (Hint: Think `while` loop!)
---
Hey Python Learners! 👋 Ready for Day 12? Today we're unlocking the power of **Modules and Packages**! 📦 These are essential for writing clean, organized, and reusable Python code. Think of modules as single files of Python code you can import, and packages as directories that group related modules together. This makes your projects much more manageable and professional. Let's learn how to structure our code like a pro! 🚀
---
```python
# --- File: math_operations.py ---
# This is a simple module
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
if __name__ == "__main__":
print(f"Running math_operations directly. 5 + 3 = {add(5, 3)}")
# --- File: my_package/__init__.py ---
# This empty file tells Python that 'my_package' is a package.
# --- File: my_package/string_utils.py ---
# This is a module inside 'my_package'
def reverse_string(s):
"""Reverses a given string."""
return s[::-1]
def capitalize_first(s):
"""Capitalizes the first letter of a string."""
return s.capitalize()
# --- File: main.py ---
# This script will use our module and package
# Make sure math_operations.py and the 'my_package' directory are in the same directory as main.py
import math_operations
from my_package import string_utils
print("--- Using math_operations module ---")
result_add = math_operations.add(10, 5)
print(f"10 + 5 = {result_add}")
result_sub = math_operations.subtract(10, 5)
print(f"10 - 5 = {result_sub}")
print("n--- Using my_package/string_utils module ---")
original_str = "hello python"
reversed_str = string_utils.reverse_string(original_str)
print(f"'{original_str}' reversed is: '{reversed_str}'")
capitalized_str = string_utils.capitalize_first(original_str)
print(f"'{original_str}' capitalized first is: '{capitalized_str}'")
```
---
Output example:
```
--- Using math_operations module ---
10 + 5 = 15
10 - 5 = 5
--- Using my_package/string_utils module ---
'hello python' reversed is: 'nohtyp olleh'
'hello python' capitalized first is: 'Hello python'
```
---
💡 Challenge Time!
Create a new module called `time_utils.py` with a function `get_current_datetime()` that returns the current date and time (you'll need the `datetime` module!). Then, import `time_utils` into `main.py` and call your new function, printing its result. Share your solution in the comments! 👇
---
---
```python
# --- File: math_operations.py ---
# This is a simple module
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the difference of two numbers."""
return a - b
if __name__ == "__main__":
print(f"Running math_operations directly. 5 + 3 = {add(5, 3)}")
# --- File: my_package/__init__.py ---
# This empty file tells Python that 'my_package' is a package.
# --- File: my_package/string_utils.py ---
# This is a module inside 'my_package'
def reverse_string(s):
"""Reverses a given string."""
return s[::-1]
def capitalize_first(s):
"""Capitalizes the first letter of a string."""
return s.capitalize()
# --- File: main.py ---
# This script will use our module and package
# Make sure math_operations.py and the 'my_package' directory are in the same directory as main.py
import math_operations
from my_package import string_utils
print("--- Using math_operations module ---")
result_add = math_operations.add(10, 5)
print(f"10 + 5 = {result_add}")
result_sub = math_operations.subtract(10, 5)
print(f"10 - 5 = {result_sub}")
print("n--- Using my_package/string_utils module ---")
original_str = "hello python"
reversed_str = string_utils.reverse_string(original_str)
print(f"'{original_str}' reversed is: '{reversed_str}'")
capitalized_str = string_utils.capitalize_first(original_str)
print(f"'{original_str}' capitalized first is: '{capitalized_str}'")
```
---
Output example:
```
--- Using math_operations module ---
10 + 5 = 15
10 - 5 = 5
--- Using my_package/string_utils module ---
'hello python' reversed is: 'nohtyp olleh'
'hello python' capitalized first is: 'Hello python'
```
---
💡 Challenge Time!
Create a new module called `time_utils.py` with a function `get_current_datetime()` that returns the current date and time (you'll need the `datetime` module!). Then, import `time_utils` into `main.py` and call your new function, printing its result. Share your solution in the comments! 👇
---