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
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! 🐦
Day 14: Inheritance and Polymorphism \- Code & Output
Here's your Telegram post for Day 15 of your Python learning series!

---

🚀 Day 15: Dive into Python Libraries! 📚 Today, we're unlocking the power of external modules by introducing you to the incredible `requests` library! 🌐 Ever wanted to fetch data from the internet or interact with web APIs? `requests` makes it super easy and intuitive. Say goodbye to complex HTTP handling and hello to elegant web interactions! Let's get started with our first web request!

```python
import requests

# Make a GET request to a placeholder API
# This fetches data for post with ID 1
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")

print(f"Status Code: {response.status_code}")
print(f"Content-Type: {response.headers['content-type']}") # Access specific header
print("Response JSON:")
print(response.json()) # Print the JSON content as a Python dictionary
```

Output example:
```
Status Code: 200
Content-Type: application/json; charset=utf-8
Response JSON:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto'}
```

💡 **Your Challenge:**
Modify the code to make a `GET` request to `https://api.ipify.org?format=json` and print *only* your public IP address from the JSON response. Hint: The response will be a dictionary, and you'll need to access a specific key! 🕵️‍♀️

---
Day 15: Introduction to Python Libraries \(requests\) \- Code & Output
Hey Python Learners! 👋

It's Day 16, and we're unlocking the power of the internet! 🌐 Today, we're diving into **Working with APIs (Application Programming Interfaces)**. Ever wondered how apps get real-time data like weather, stock prices, or news? It's often through APIs! Python makes it incredibly easy to interact with these services using the `requests` library. Get ready to fetch data from the web like a pro! 🚀 Let's make our Python scripts communicate with the world! ✨

```python
import requests

# Define the API endpoint we want to access
# This is a public API for placeholder data
url = "https://jsonplaceholder.typicode.com/todos/1"

print(f"Making a GET request to: {url}")

try:
# Make a GET request to the API
response = requests.get(url)

# Check if the request was successful (status code 200 means OK)
if response.status_code == 200:
# Parse the JSON response into a Python dictionary
todo_item = response.json()

print("nSuccessfully fetched data! ✅")
print(f"Item ID: {todo_item['id']}")
print(f"User ID: {todo_item['userId']}")
print(f"Title: {todo_item['title']}")
print(f"Completed: {todo_item['completed']}")
else:
print(f"nError fetching data. Status code: {response.status_code}")
print(f"Response text: {response.text}")

except requests.exceptions.RequestException as e:
print(f"nAn error occurred during the request: {e}")

```

Output example:
```
Making a GET request to: https://jsonplaceholder.typicode.com/todos/1

Successfully fetched data! ✅
Item ID: 1
User ID: 1
Title: delectus aut autem
Completed: False
```

### Your Small Challenge! 👇

Can you modify the code to fetch a different resource? Try changing the `url` to `"https://jsonplaceholder.typicode.com/posts/2"` and print out the `title` and `body` of that post. What do you get? Share your results! 💡

---
Day 16: Working with APIs \- Code & Output
Which Python library is commonly used for making HTTP requests to interact with web APIs?
Anonymous Quiz
0%
requests
0%
urllib
100%
http.client
0%
socket
Hello Pythonistas! 👋 Day 17 is here, and we're diving into the world of JSON! 🌐 JSON (JavaScript Object Notation) is a lightweight, human-readable format for data interchange, super common in web APIs and configuration files. Today, we'll master how Python's built-in `json` module helps us effortlessly convert JSON strings into Python dictionaries and lists, and back again. Get ready to handle external data like a pro! 💻✨

---

```python
import json

# 1. Parsing JSON string to a Python dictionary
json_data_string = '''
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": ["Python Basics", "Web Development"],
"contact": {
"email": "alice@example.com",
"phone": null
}
}
'''
print("--- Parsing JSON string to Python dictionary ---")
data = json.loads(json_data_string)
print(f"Type after parsing: {type(data)}")
print(f"Name: {data['name']}")
print(f"First course: {data['courses'][0]}")
print(f"Email: {data['contact']['email']}n")

# 2. Converting a Python dictionary to a JSON string
python_dict_data = {
"product_id": "P001",
"product_name": "Laptop",
"price": 1200.50,
"available": True,
"tags": ["electronics", "computers", "portable"]
}

print("--- Converting Python dictionary to JSON string ---")
# Using indent for pretty-printing the JSON string
json_output_string = json.dumps(python_dict_data, indent=2)
print(f"Type after converting: {type(json_output_string)}")
print(json_output_string)
```

---

Output example:
```
--- Parsing JSON string to Python dictionary ---
Type after parsing: <class 'dict'>
Name: Alice
First course: Python Basics
Email: alice@example.com

--- Converting Python dictionary to JSON string ---
Type after converting: <class 'str'>
{
"product_id": "P001",
"product_name": "Laptop",
"price": 1200.50,
"available": true,
"tags": [
"electronics",
"computers",
"portable"
]
}
```

---

### Challenge for the Day! 🚀
Create a Python dictionary representing your favorite movie with keys like `title`, `director`, `year`, and `genres` (a list). Convert this dictionary into a JSON formatted string and print it. Then, parse that JSON string back into a Python dictionary and print just the movie's `director`.

---

Here's your quiz question for today's lesson:
Day 17: JSON Data Handling \- Code & Output
Which Python `json` module function is used to convert a JSON formatted string into a Python dictionary or list?
Anonymous Quiz
100%
json.load()
0%
json.loads()
0%
json.dump()
Day 18: Regular Expressions \- Code & Output
Which `re` module function is used to find all non-overlapping matches of a pattern in a string and returns them as a list of strings?
Anonymous Quiz
0%
re.match()
0%
re.findall()
0%
re.sub()
🚀 Day 19: Mastering Virtual Environments! 🐍

Ever struggled with conflicting package versions or a messy global Python setup? Virtual environments are your superpower! They create isolated spaces for your Python projects, ensuring each project has its own set of dependencies without interfering with others. This is essential for clean, manageable, and reproducible development. Let's learn how to create and use them today! ✨

```python
# 1. Create a virtual environment (replace 'myproject_env' with your desired name)
# This creates a folder named 'myproject_env' containing a Python interpreter
# and pip specifically for this environment.
python3 -m venv myproject_env

# 2. Activate the virtual environment
# (Linux/macOS)
source myproject_env/bin/activate

# (Windows PowerShell)
# . .myproject_envScriptsActivate.ps1

# (Windows Command Prompt)
# .myproject_envScriptsactivate.bat

# Note: Once activated, your terminal prompt will usually show the environment name
# (e.g., (myproject_env) user@machine:~$ )

# 3. Install a package *within* this active environment
pip install requests

# 4. See installed packages in this *specific* environment
pip freeze

# 5. Deactivate the virtual environment when you're done
deactivate
```

Output example:
```
user@machine:~$ python3 -m venv myproject_env
user@machine:~$ source myproject_env/bin/activate
(myproject_env) user@machine:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 kB 3.1 MB/s eta 0:00:00
... (other dependencies like urllib3, certifi, etc.) ...
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(myproject_env) user@machine:~$ pip freeze
certifi==2023.11.17
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.1.0
(myproject_env) user@machine:~$ deactivate
user@machine:~$
```

Small challenge: After activating your virtual environment, try installing a different package (e.g., `numpy` or `flask`). Then, use `pip freeze` again to see what's new! Don't forget to `deactivate` when you're done. Share your `pip freeze` output in the comments! 💡

---