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

---
Day 19: Virtual Environments \- Code & Output
Here's your Telegram post and quiz question!

---

Hey Python learners! 👋

Ever wondered how to manage dates and times in your Python programs? ⏰ Today, on Day 20 of our series, we dive deep into the incredibly powerful `datetime` module! From getting the current time to calculating durations and formatting dates, this module is your go-to for all temporal tasks. Let's make your programs time-aware! 🗓️

```python
from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(f"Current Date & Time: {now}")

# Create a specific date and time
specific_date = datetime(2023, 1, 15, 10, 30, 0)
print(f"Specific Date: {specific_date}")

# Format dates into a string (strftime)
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted Date (YYYY-MM-DD HH:MM:SS): {formatted_date}")

# Format with more detail
user_friendly_date = now.strftime("%A, %B %d, %Y at %I:%M %p")
print(f"User-Friendly Date: {user_friendly_date}")

# Parse a string into a datetime object (strptime)
date_string = "2024-07-20 14:00:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Date from string: {parsed_date}")

# Calculate time differences (timedelta)
time_difference = now - specific_date
print(f"Time difference since specific date: {time_difference}")

# Add or subtract time
future_date = now + timedelta(days=7, hours=3)
print(f"Date 7 days and 3 hours from now: {future_date}")

# Accessing components
print(f"Current Year: {now.year}, Month: {now.month}, Day: {now.day}")
```

Output example:
```
Current Date & Time: 2024-07-20 10:35:45.123456
Specific Date: 2023-01-15 10:30:00
Formatted Date (YYYY-MM-DD HH:MM:SS): 2024-07-20 10:35:45
User-Friendly Date: Saturday, July 20, 2024 at 10:35 AM
Parsed Date from string: 2024-07-20 14:00:00
Time difference since specific date: 552 days, 0:05:45.123456
Date 7 days and 3 hours from now: 2024-07-27 13:35:45.123456
Current Year: 2024, Month: 7, Day: 20
```

### 🧠 Small Challenge:
Can you write a short Python snippet to calculate how many days are left until Christmas 2024? (Hint: You'll need `datetime` for Christmas, `datetime.now()` for today, and `timedelta` to find the difference!)

Happy coding, and see you tomorrow! 🚀

---

### Quiz Question:
Day 20: Working with Dates and Times \- Code & Output
What will be the output of `datetime(2024, 7, 20, 15, 30).strftime('%d-%m-%Y %I:%M %p')`?
Anonymous Quiz
100%
20-07-2024 03:30 PM
0%
20-07-2024 15:30 PM
0%
07-20-2024 03:30 PM
0%
20-07-2024 03:30 AM
Here's your Telegram post and quiz question for Day 21 on Decorators!

---

🥳 Day 21 already! Today, we're diving into one of Python's most elegant and powerful features: *Decorators*! ✨

Think of them as wrappers that allow you to modify or enhance the behavior of a function or a method without permanently changing its code. They're super handy for adding extra functionality like logging, timing, authentication, or input validation. Let's unravel their magic! 🎩

```python
import time
import functools

# Our first decorator: A simple timer
def timer_decorator(func):
@functools.wraps(func) # Important for preserving original func metadata
def wrapper(*args, **kwargs):
start_time = time.perf_counter() # Record start time
result = func(*args, **kwargs) # Execute the original function
end_time = time.perf_counter() # Record end time
print(f"⌛️ Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds.")
return result
return wrapper

# Applying the decorator using the @ syntax
@timer_decorator
def calculate_sum(n):
"""Calculates the sum of numbers up to n."""
total = 0
for i in range(n + 1):
total += i
time.sleep(0.01) # Simulate some work
return total

@timer_decorator
def greet(name):
"""Greets a person."""
time.sleep(0.005) # Simulate some work
return f"Hello, {name}!"

# --- Using the decorated functions ---
print(f"Sum: {calculate_sum(100000)}")
print(greet("Pythonista"))
```

Output example:
```
⌛️ Function 'calculate_sum' executed in 0.0112 seconds.
Sum: 5000050000
⌛️ Function 'greet' executed in 0.0053 seconds.
Hello, Pythonista!
```

Challenging you: 💪 Can you create a *`logger_decorator`* that prints the arguments a function received before executing it? For example, `Calling 'my_func' with args=(1, 2), kwargs={'name': 'Alice'}`.

---
Day 21: Decorators \- Code & Output