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
👋 Hey Python learners! Day 13 is here, and we're diving into one of the most powerful concepts: **Object-Oriented Programming (OOP)!** 🏗️ Today, we'll demystify **Classes and Objects**.

Think of a Class as a blueprint (like for a house 🏡), and an Object as a real-world item built from that blueprint (the actual house!). It's how we build structured, organized, and reusable code. Get ready to create your own custom data types! ✨ Let's build some objects!

```python
class Car:
# The __init__ method is called automatically when a new object is created
def __init__(self, make, model, year):
self.make = make # Assigning 'make' to the object's attribute
self.model = model # Assigning 'model' to the object's attribute
self.year = year # Assigning 'year' to the object's attribute
print(f"A new {self.year} {self.make} {self.model} has been created!")

# A method is a function that belongs to an object
def display_info(self):
return f"Car details: {self.year} {self.make} {self.model}"

# Creating objects (instances) of the Car class
my_car = Car("Toyota", "Camry", 2022)
your_car = Car("Honda", "Civic", 2023)

# Accessing attributes and calling methods for our objects
print(my_car.display_info())
print(f"My car's make: {my_car.make}")
print(your_car.display_info())
print(f"Your car's model: {your_car.model}")
```

Output example:
```
A new 2022 Toyota Camry has been created!
A new 2023 Honda Civic has been created!
Car details: 2022 Toyota Camry
My car's make: Toyota
Car details: 2023 Honda Civic
Your car's model: Civic
```

🚀 **Your Challenge:** Can you add a new method called `honk()` to our `Car` class that simply prints 'Beep! Beep!'? Then, call this new method for both `my_car` and `your_car`! Show us your modified code! 👇

---
Day 13: Object\-Oriented Programming \(Classes and Objects\) \- Code & Output
🚀 Day 14: Unlocking the power of Object-Oriented Programming with **Inheritance and Polymorphism**! 🧬 These aren't just fancy words; they're fundamental concepts that let you write incredibly reusable, flexible, and maintainable code.

Inheritance allows you to create new classes (child classes) that build upon existing ones (parent classes), inheriting their attributes and methods. Polymorphism, on the other hand, enables objects of different classes to be treated uniformly through a common interface. Let's see them in action! ✨

```python
# --- Inheritance Example ---
class Animal:
def __init__(self, name):
self.name = name

def make_sound(self):
return f"{self.name} makes a generic sound."

class Dog(Animal): # Dog inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} barks loudly!"

class Cat(Animal): # Cat inherits from Animal
def make_sound(self): # Method overriding
return f"{self.name} purrs softly."

# --- Polymorphism Example ---
def animal_party(animals):
"""
This function demonstrates polymorphism:
it can work with any object that has a 'make_sound' method,
regardless of its specific class (Dog, Cat, or Animal).
"""
for animal in animals:
print(animal.make_sound())

# Create objects
generic_animal = Animal("Creature")
doggy = Dog("Buddy")
kitty = Cat("Whiskers")

print("--- Demonstrating Inheritance and Overriding ---")
print(generic_animal.make_sound())
print(doggy.make_sound())
print(kitty.make_sound())

print("n--- Demonstrating Polymorphism ---")
zoo_animals = [doggy, kitty, generic_animal]
animal_party(zoo_animals) # All objects respond to make_sound() in their own way
```

Output example:
```
--- Demonstrating Inheritance and Overriding ---
Creature makes a generic sound.
Buddy barks loudly!
Whiskers purrs softly.

--- Demonstrating Polymorphism ---
Buddy barks loudly!
Whiskers purrs softly.
Creature makes a generic sound.
```

💡 **Challenge:** Create a new class `Lion` that inherits from `Animal`. Make it override `make_sound` to return "roars mightily!". Then, add a `Lion` object to the `zoo_animals` list and call `animal_party` again. See the mighty roar! 🦁

---
Day 14: Inheritance and Polymorphism \- Code & Output
Here's your Telegram post for Day 15 of the Python learning series!

---

🚀 Day 15: Dive into the world of Python Libraries! Today, we're unlocking the power of the `requests` library. Ever wanted your Python scripts to interact with websites, fetch data, or send information? `requests` makes web interactions incredibly simple and elegant. It's an indispensable tool for web scraping, API interactions, and much more. Let's make some requests! 🌐

```python
import requests # Import the requests library

# Define the URL for a public API endpoint
# This API provides fake data for testing purposes
url = "https://jsonplaceholder.typicode.com/todos/1"

# Make a GET request to the URL
response = requests.get(url)

# Print the HTTP status code
print(f"Status Code: {response.status_code}")

# Check if the request was successful (status code 200 indicates success)
if response.status_code == 200:
# Print the JSON response content
# .json() method automatically parses the JSON response into a Python dictionary
print("Response JSON:")
print(response.json())
else:
print(f"Request failed with status code {response.status_code}")

```

Output example:
```
Status Code: 200
Response JSON:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
```

💡 **Challenge Time!** Try modifying the `url` in the code to `https://jsonplaceholder.typicode.com/posts/2`. What kind of data do you get back? Can you also try to print `response.headers` to see the HTTP response headers? Share your findings! 👇

---
Day 15: Introduction to Python Libraries \(requests\) \- Code & Output
Here's your Telegram post for the Python learning series:

---

👋 Hey Python learners!

Day 16 is here, and we're diving into the exciting world of **Working with APIs**! 🌐 Ever wondered how apps like weather apps or social media feeds get their data? It's all thanks to APIs (Application Programming Interfaces)! They allow different software applications to communicate with each other. In Python, the `requests` library is your best friend for interacting with web APIs. Today, we'll learn how to fetch data from an API using a simple GET request. Let's get connected! 📡🚀

```python
import requests

# Define the API endpoint URL
url = "https://api.chucknorris.io/jokes/random"

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

# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()

# Extract the joke from the data
joke = data['value']

print("Chuck Norris Joke:")
print(joke)
else:
print(f"Error fetching joke: {response.status_code}")
print(response.text) # Print error details if available

except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")

```

Output example:
```
Chuck Norris Joke:
Chuck Norris taught a blind man to see. Not to read, but to see.
```

**Challenge:**
Try fetching a random Kanye West quote from `https://api.kanye.rest/` and print it out! 🤔 You'll notice the structure of the JSON response might be slightly different. Good luck!

---
Day 16: Working with APIs \- Code & Output
Which `requests` library method is typically used to retrieve data from a web API?
Anonymous Quiz
0%
requests.send()
0%
requests.get()
0%
requests.fetch()
Here's your Telegram post for Day 17!

---

Hey Pythonistas! 👋 Day 17 is here, and we're diving into a cornerstone of modern web development and data exchange: **JSON** (JavaScript Object Notation). 🌐 It's the lightweight, human-readable format used extensively for APIs, configuration files, and more. Python makes handling JSON incredibly easy with its built-in `json` module. You'll learn how to convert Python dictionaries/lists to JSON strings and files, and vice versa. Let's unlock the power of data interchange! 🚀

```python
import json
import os

# --- Part 1: Python objects to JSON strings (serialization) ---
# A Python dictionary
user_data = {
"name": "Alex",
"age": 28,
"is_active": True,
"skills": ["Python", "API", "Databases"],
"preferences": {"theme": "dark", "notifications": True},
"last_login": None
}

# Convert Python dict to JSON string (dumps = "dump string")
# 'indent=4' makes the JSON output pretty-printed for readability
json_string = json.dumps(user_data, indent=4)
print("--- Python Dictionary to JSON String ---")
print(json_string)

# --- Part 2: JSON strings to Python objects (deserialization) ---
# A JSON string
json_text = '''
{
"product": "Wireless Mouse",
"price": 25.99,
"available": true,
"ratings": 4.5
}
'''

# Convert JSON string to Python dictionary (loads = "load string")
product_dict = json.loads(json_text)
print("n--- JSON String to Python Dictionary ---")
print(f"Product: {product_dict['product']}")
print(f"Price: ${product_dict['price']}")
print(f"Is available: {product_dict['available']}")
print(f"Type of product_dict: {type(product_dict)}")

# --- Part 3: Python objects to JSON files (serialization to file) ---
file_name = "my_data.json"
config_data = {
"app_name": "MyCoolApp",
"version": "1.0.0",
"settings": {
"log_level": "INFO",
"max_connections": 100
}
}

# Write Python dict to a JSON file (dump = "dump to file")
with open(file_name, 'w') as f:
json.dump(config_data, f, indent=4)
print(f"n--- Python Dictionary written to '{file_name}' ---")

# --- Part 4: JSON files to Python objects (deserialization from file) ---
# Read JSON from a file into a Python dictionary (load = "load from file")
if os.path.exists(file_name):
with open(file_name, 'r') as f:
loaded_config = json.load(f)
print(f"--- JSON from '{file_name}' loaded into Python Dictionary ---")
print(f"App Name: {loaded_config['app_name']}")
print(f"Log Level: {loaded_config['settings']['log_level']}")

# Clean up the created file
os.remove(file_name)
print(f"'{file_name}' removed.")
else:
print(f"Error: '{file_name}' not found for loading.")
```

Output example:
```
--- Python Dictionary to JSON String ---
{
"name": "Alex",
"age": 28,
"is_active": true,
"skills": [
"Python",
"API",
"Databases"
],
"preferences": {
"theme": "dark",
"notifications": true
},
"last_login": null
}

--- JSON String to Python Dictionary ---
Product: Wireless Mouse
Price: $25.99
Is available: True
Type of product_dict: <class 'dict'>

--- Python Dictionary written to 'my_data.json' ---

--- JSON from 'my_data.json' loaded into Python Dictionary ---
App Name: MyCoolApp
Log Level: INFO
'my_data.json' removed.
```

### Your Challenge! 🧠💡
Create a list of Python dictionaries, where each dictionary represents an employee with keys like `id`, `name`, `department`, and `salary`. Convert this list into a JSON string and print it. Then, write this same data to a file named `employees.json`. Finally, load `employees.json` back into a Python list and print the names of all employees who work in the "Marketing" department. Don't forget to clean up the file!

---

### Quiz Question ❓
Day 17: JSON Data Handling \- Code & Output
Which of the following Python data types is *NOT* directly equivalent to a JSON data type?
Anonymous Quiz
0%
String
0%
List
0%
Tuple
100%
Dictionary
Here's your Telegram post for Day 18: Regular Expressions!

---

🚀 Day 18: Regular Expressions! 🤯 Get ready to master the art of text pattern matching with Python's powerful `re` module. Regular Expressions (RegEx) are essential for searching, extracting, and manipulating text based on complex patterns. Whether it's validating user input or parsing logs, RegEx is your go-to tool. Let's dive into finding patterns today! 🔍📝

```python
import re

text = "Hello Python learners! Today is Day 18. We're diving into Regular Expressions. Find all words, numbers, and underscores!"

# Pattern 1: Find all "words" (alphanumeric characters + underscore)
# w matches any word character (a-z, A-Z, 0-9, _)
# + matches one or more occurrences of the preceding character/group
pattern_words = r'w+'
found_words = re.findall(pattern_words, text)

print("Found 'words':", found_words)

# Pattern 2: Find all numbers
# d matches any digit (0-9)
pattern_numbers = r'd+'
found_numbers = re.findall(pattern_numbers, text)

print("Found numbers:", found_numbers)
```

Output example:
```
Found 'words': ['Hello', 'Python', 'learners', 'Today', 'is', 'Day', '18', 'We', 're', 'diving', 'into', 'Regular', 'Expressions', 'Find', 'all', 'words', 'numbers', 'and', 'underscores']
Found numbers: ['18']
```

💡 **Small Challenge:** Can you modify the code to find all words in the `text` variable that *start* with 'R' or 'r'? (Hint: Look into `^` for start of string/line and character sets `[]`!)

---
Day 18: Regular Expressions \- Code & Output
Which `re` module function is typically used to find *all* non-overlapping matches of a pattern in a string and return them as a list of strings?
Anonymous Quiz
0%
re.findall()
0%
re.match()
0%
re.sub()
🚀 Day 19: Mastering Python Virtual Environments! 🚀

Ever faced "dependency hell" where one project needs a different package version than another? Say goodbye to conflicts! Today, we're diving into virtual environments – your secret weapon for isolating project dependencies. Keep your projects clean, organized, and conflict-free. Let's set up our isolated workspaces! ✨📦

Here's how you use them:

```python
# 1. Create a virtual environment (replace 'my_project_env' with your desired name)
python -m venv my_project_env

# 2. Activate the virtual environment
# On macOS/Linux:
source my_project_env/bin/activate
# On Windows (Command Prompt):
my_project_envScriptsactivate
# On Windows (PowerShell):
my_project_envScriptsActivate.ps1

# 3. Install a package inside the activated environment
pip install requests

# 4. See installed packages (it will only show packages in this venv)
pip list

# 5. Deactivate the virtual environment
deactivate
```

Output example:
```
(base) user@host:~$ python -m venv my_project_env
(base) user@host:~$ source my_project_env/bin/activate
(my_project_env) user@host:~$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 kB 390.6 kB/s eta 0:00:00
Collecting idna<4,>=2.5
Downloading idna-3.6-py3-none-any.whl (61 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.8/61.8 kB 403.6 kB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
Downloading charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (119 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 119.8/119.8 kB 506.7 kB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
Downloading urllib3-2.1.0-py3-none-any.whl (104 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 104.5/104.5 kB 558.1 kB/s eta 0:00:00
Collecting certifi>=2017.4.17
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 162.5/162.5 kB 588.6 kB/s eta 0:00:00
Installing collected packages: idna, charset-normalizer, urllib3, certifi, requests
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
(my_project_env) user@host:~$ pip list
Package Version
---------------- ---------
certifi 2023.11.17
charset-normalizer 3.3.2
idna 3.6
pip 23.3.1
requests 2.31.0
setuptools 68.2.2
urllib3 2.1.0
(my_project_env) user@host:~$ deactivate
(base) user@host:~$
```

💡 **Your Challenge:**
1. Create a new virtual environment called `my_challenge_env`.
2. Activate it.
3. Install the `numpy` library using `pip`.
4. Confirm `numpy` is listed using `pip list`.
5. Deactivate your environment.
Share your success in the comments! 🎉
Day 19: Virtual Environments \- Code & Output