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
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!

---
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! 😉)

---
Day 8: Dictionaries and Sets \- Code & Output
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: String Manipulation \- Code & Output
What will be the output of the following Python code?
```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()!)

---
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!
Day 11: Error Handling \(try, except\) \- Code & Output
Here's your Telegram post and quiz question!

---

🚀 Day 12 is here, Pythonistas! Today, we're unlocking the power of **Python Modules and Packages**! 📦✨

No more monolithic scripts! Modules help us organize our code into reusable files, making our projects cleaner, more manageable, and incredibly efficient. Think of them as toolboxes you can bring into any project. Let's dive in and see how easy it is to bring external functionality into your projects! 👇

```python
# --- my_module.py ---
# This file acts as our custom module

PI = 3.14159

def greet(name):
"""Greets a user."""
return f"Hello, {name}! Welcome to our module."

def add(a, b):
"""Adds two numbers."""
return a + b

def multiply(a, b):
"""Multiplies two numbers."""
return a * b

# --- main_app.py ---
# This file imports and uses functions/variables from my_module.py
# Make sure both files are in the same directory!

import my_module
from my_module import add, PI as MY_PI_VALUE # Can rename imported items

print("--- Using 'import my_module' ---")
message = my_module.greet("Alice")
print(message)
print(f"PI from my_module: {my_module.PI}")
print(f"Product of 4 and 6: {my_module.multiply(4, 6)}")

print("n--- Using 'from my_module import ...' ---")
sum_result = add(10, 5) # No need for my_module.add
print(f"Sum of 10 and 5: {sum_result}")
print(f"PI (renamed import): {MY_PI_VALUE}")

# You can even see what's inside a module!
print("n--- Items in my_module after import (top 5) ---")
print([item for item in dir(my_module) if not item.startswith('__')][:5])
```

Output example:
```
--- Using 'import my_module' ---
Hello, Alice! Welcome to our module.
PI from my_module: 3.14159
Product of 4 and 6: 24

--- Using 'from my_module import ...' ---
Sum of 10 and 5: 15
PI (renamed import): 3.14159

--- Items in my_module after import (top 5) ---
['PI', 'add', 'greet', 'multiply']
```

**Challenge Time! 🧠**
Create a new Python file called `string_helpers.py`. Inside it, define two functions:
1. `reverse_string(text)`: Returns the input string reversed.
2. `is_palindrome(text)`: Returns `True` if the string is a palindrome (reads the same forwards and backward, ignoring case), `False` otherwise.
Then, in your `main_app.py` (or a new file), import these functions and test them with a few strings! Share your solutions! 👇

---
Day 12: Modules and Packages \- Code & Output
Here's your Telegram post for Day 13 of the Python learning series:

---

🚀 **Day 13: Object-Oriented Programming (Classes and Objects)** 🏗️

Ready to build more organized and reusable Python code? Today, we're diving into the powerful world of Object-Oriented Programming (OOP)! 💡

Think of a **class** as a blueprint – a design for creating something. An **object** is then an actual item built from that blueprint. We'll learn how to define classes, create objects (instances), and give them attributes (data) and methods (functions that perform actions). This concept is fundamental to writing clean, scalable, and maintainable applications! Let's get started! 👇

```python
# Define a simple class called 'Dog'
class Dog:
# The __init__ method is a constructor. It's called when a new object is created.
# 'self' refers to the instance of the class itself.
def __init__(self, name, breed, age):
self.name = name # Assign arguments to instance attributes
self.breed = breed
self.age = age

# A method (function) that belongs to the Dog class
def bark(self):
return f"{self.name} says Woof! Woof!"

# Another method to display dog's info
def display_info(self):
return f"This is {self.name}, a {self.age}-year-old {self.breed}."

# Create objects (instances) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever", 3)
your_dog = Dog("Lucy", "Beagle", 2)

# Access attributes of the objects
print(f"My dog's name: {my_dog.name}")
print(f"Your dog's breed: {your_dog.breed}")

# Call methods on the objects
print(my_dog.bark())
print(your_dog.display_info())
```

Output example:
```
My dog's name: Buddy
Your dog's breed: Beagle
Buddy says Woof! Woof!
This is Lucy, a 2-year-old Beagle.
```

🐾 **Small Challenge:**
Add another method to the `Dog` class, like `celebrate_birthday()`, which increments the dog's `age` attribute and prints a celebratory message! Try calling it for `my_dog`! 🎉

---
Day 13: Object\-Oriented Programming \(Classes and Objects\) \- Code & Output
🚀 Day 14 of our Python journey is here! Today, we're diving into the powerful concepts of *Inheritance* and *Polymorphism*. 🐍 Inheritance allows us to build new classes based on existing ones, reusing code and creating a clear hierarchy. Polymorphism, on the other hand, lets objects of different classes be treated as objects of a common type, responding to the same method calls in their own unique ways. Get ready to write more organized and flexible code! ✨

```python
class Animal:
def __init__(self, name):
self.name = name

def make_sound(self):
return "Generic animal sound"

def describe(self):
return f"I am a {self.__class__.__name__} named {self.name}."

class Dog(Animal): # Inheritance: Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name) # Call parent's constructor
self.breed = breed

def make_sound(self): # Polymorphism: Overriding parent method
return "Woof! Woof!"

def fetch(self):
return f"{self.name} is fetching the ball!"

class Cat(Animal): # Inheritance: Cat inherits from Animal
def __init__(self, name, color):
super().__init__(name)
self.color = color

def make_sound(self): # Polymorphism: Overriding parent method
return "Meow!"

def scratch(self):
return f"{self.name} is scratching the couch."

# Demonstrating Inheritance and Polymorphism
print("--- Inheritance Example ---")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.describe()) # Inherited method
print(my_dog.make_sound()) # Overridden method
print(my_dog.fetch()) # Dog's specific method

my_cat = Cat("Whiskers", "Tabby")
print(my_cat.describe()) # Inherited method
print(my_cat.make_sound()) # Overridden method
print(my_cat.scratch()) # Cat's specific method

print("n--- Polymorphism Example ---")
animals = [
Dog("Max", "German Shepherd"),
Cat("Bella", "Siamese"),
Animal("Unknown Creature") # An instance of the base class
]

for animal in animals:
print(f"{animal.name} says: {animal.make_sound()}")
```

Output example:
```
--- Inheritance Example ---
I am a Dog named Buddy.
Woof! Woof!
Buddy is fetching the ball!
I am a Cat named Whiskers.
Meow!
Whiskers is scratching the couch.

--- Polymorphism Example ---
Max says: Woof! Woof!
Bella says: Meow!
Unknown Creature says: Generic animal sound
```

**Small Challenge:**
Can you create another animal class, like `Bird`, that inherits from `Animal` and overrides the `make_sound` method? Add an instance of your `Bird` to the `animals` list and observe the polymorphic behavior! 🐦