Python basic to advance
43 subscribers
131 photos
98 links
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
Download Telegram
What is the output of the following Python expression: `5 * 2 + 8 / 4`?
Anonymous Quiz
0%
12.0
0%
12
0%
7.0
0%
7
🎉 Day 5: Let's Get Loopy! 🎉

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

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

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

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

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

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

Counting down with 'while' loop:
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀
```

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

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

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

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

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

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

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

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

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

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

---

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

---

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

---

👋 Day 7 of our Python journey is here! Today, we're diving into two fundamental data structures: **Lists** 📝 and **Tuples** 🧐.

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

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

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

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

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

print("-" * 20)

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

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

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

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

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

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

---

🚀 **Day 8: Unlocking Dictionaries & Sets!** 🧠

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

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

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

Let's see them in action! 👇

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---
Day 9: String Manipulation \- Code & Output
What will be the output of `text.split("o")` for `text = "hello world"`?
Anonymous Quiz
0%
['hell', ' w', 'rld']
0%
['hell', ' world']
0%
['h', 'll', ' w', 'rld']
0%
['hell', 'o', ' w', 'rld']
Here's your Telegram post for Day 10 on File I/O!

---

📣 **Day 10: Unlocking File I/O in Python!** 📂

Hey there, Python Explorers! 👋 On Day 10, we're diving into how Python interacts with files on your computer! This is crucial for storing data, loading configurations, or processing logs. Imagine saving game scores, user settings, or processing large datasets – File I/O makes it all possible.

Today's code will show you how to write content to a new file, read its content back, and even add more data to an existing file. We'll use the `with open(...)` statement, which is your best friend for safely handling files, ensuring they close automatically. Let's get hands-on! 💾✍️📖

```python
# --- Python File I/O Example ---

file_name = "my_python_notes.txt"

# 1. Writing to a file (mode 'w' - writes from scratch, overwrites if exists)
print(f"Creating/overwriting '{file_name}' and writing content...")
with open(file_name, 'w') as file:
file.write("Hello, Python learners!n")
file.write("Welcome to Day 10 of our series.n")
file.write("File I/O is powerful! 💪n")
print("Content written successfully.")

# 2. Reading from a file (mode 'r')
print(f"nReading content from '{file_name}'...")
with open(file_name, 'r') as file:
content = file.read()
print("--- Start of File Content ---")
print(content)
print("--- End of File Content ---n")

# 3. Appending to a file (mode 'a' - adds to the end)
print(f"Appending new content to '{file_name}'...")
with open(file_name, 'a') as file:
file.write("This line was appended later.n")
file.write("See how easy it is to add more! ✨")
print("Content appended successfully.")

# 4. Reading again to see the appended content
print(f"nReading updated content from '{file_name}'...")
with open(file_name, 'r') as file:
updated_content = file.read()
print("--- Start of Updated File Content ---")
print(updated_content)
print("--- End of Updated File Content ---")

```

Output example:
```
Creating/overwriting 'my_python_notes.txt' and writing content...
Content written successfully.

Reading content from 'my_python_notes.txt'...
--- Start of File Content ---
Hello, Python learners!
Welcome to Day 10 of our series.
File I/O is powerful! 💪

--- End of File Content ---

Appending new content to 'my_python_notes.txt'...
Content appended successfully.

Reading updated content from 'my_python_notes.txt'...
--- Start of Updated File Content ---
Hello, Python learners!
Welcome to Day 10 of our series.
File I/O is powerful! 💪
This line was appended later.
See how easy it is to add more! ✨
--- End of Updated File Content ---
```

### 🧠 Small Challenge:
Modify the reading part of the code to read `my_python_notes.txt` line by line instead of reading the whole file at once. Can you also print each line prefixed with its line number (starting from 1)? For example:
```
1: Hello, Python learners!
2: Welcome to Day 10 of our series.
...
```
Give it a try! You might find `readlines()` or iterating directly over the file object useful. Good luck! 🚀

---

Here's your quiz question:
Day 10: File I/O \(Input/Output\) \- Code & Output
🚀 Day 11: Error Handling (try, except) 🐍

Even the best code can encounter unexpected situations – like invalid user input or network issues. Today, we're diving into **Error Handling** with `try` and `except` blocks! ✨ This powerful duo allows your programs to gracefully recover from errors instead of crashing, providing a much smoother user experience. Learn to anticipate problems and keep your code robust! 💪

```python
def safe_divide(numerator, denominator):
"""
Attempts to divide two numbers, handling common division errors.
"""
try:
result = numerator / denominator
print(f"The result of {numerator} / {denominator} is: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero! Please provide a non-zero denominator. 🚫")
except TypeError:
print("Error: Both inputs for division must be numbers. 🔢")
except Exception as e: # Catch any other unexpected errors
print(f"An unexpected error occurred: {e} 🐛")
else:
print("Division successful! 🎉")
finally:
print("Operation complete. ✅")

print("--- Example 1: Successful division ---")
safe_divide(11, 2)

print("n--- Example 2: Division by zero ---")
safe_divide(10, 0)

print("n--- Example 3: Invalid input type ---")
safe_divide(20, "five")

print("n--- Example 4: Another successful division ---")
safe_divide(15, 3)
```

Output example:
```
--- Example 1: Successful division ---
The result of 11 / 2 is: 5.5
Division successful! 🎉
Operation complete. ✅

--- Example 2: Division by zero ---
Error: Cannot divide by zero! Please provide a non-zero denominator. 🚫
Operation complete. ✅

--- Example 3: Invalid input type ---
Error: Both inputs for division must be numbers. 🔢
Operation complete. ✅

--- Example 4: Another successful division ---
The result of 15 / 3 is: 5.0
Division successful! 🎉
Operation complete. ✅
```

💡 *Your Challenge:*
Modify the `safe_divide` function to also:
1. Prompt the user to `input()` the numerator and denominator.
2. Handle `ValueError` if the user enters text that cannot be converted to a number (e.g., `int("hello")`). 🤔

---