Here's your Telegram post for Day 13 of the Python learning series:
---
🚀 Day 13: Dive into the world of Object-Oriented Programming (OOP)! 🐍 Today, we unravel the magic of Classes and Objects. Think of a Class as a blueprint 🏗️ for creating things, and an Object as a real-world item built from that blueprint. OOP helps us structure code, make it reusable, and manage complexity like a pro! Get ready to create your own custom data types. ✨
```python
class Car:
# Class attribute (shared by all instances)
wheels = 4
def __init__(self, make: str, model: str, year: int):
# Instance attributes (unique to each object)
self.make = make
self.model = model
self.year = year
self.speed = 0
print(f"A new {self.year} {self.make} {self.model} has been created!")
def accelerate(self, increment: int):
self.speed += increment
return f"The {self.make} {self.model} accelerates to {self.speed} km/h."
def brake(self, decrement: int):
self.speed = max(0, self.speed - decrement)
return f"The {self.make} {self.model} slows down to {self.speed} km/h."
def get_description(self):
return f"This is a {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
print(my_car.get_description())
print(my_car.accelerate(50))
print(my_car.brake(20))
print(f"My car's current speed: {my_car.speed} km/h")
print(f"n{your_car.get_description()}")
print(your_car.accelerate(70))
print(f"Your car has {your_car.wheels} wheels.") # Accessing a class attribute
```
Output example:
```
A new 2022 Toyota Camry has been created!
A new 2023 Honda Civic has been created!
This is a 2022 Toyota Camry.
The Toyota Camry accelerates to 50 km/h.
The Toyota Camry slows down to 30 km/h.
My car's current speed: 30 km/h
This is a 2023 Honda Civic.
The Honda Civic accelerates to 70 km/h.
Your car has 4 wheels.
```
**Challenge:**
Extend the `Car` class by adding a new method, for example, `honk()`, that prints a "Beep! Beep!" message along with the car's model. Then, create another `Car` object and try out your new method! 🚘
---
---
🚀 Day 13: Dive into the world of Object-Oriented Programming (OOP)! 🐍 Today, we unravel the magic of Classes and Objects. Think of a Class as a blueprint 🏗️ for creating things, and an Object as a real-world item built from that blueprint. OOP helps us structure code, make it reusable, and manage complexity like a pro! Get ready to create your own custom data types. ✨
```python
class Car:
# Class attribute (shared by all instances)
wheels = 4
def __init__(self, make: str, model: str, year: int):
# Instance attributes (unique to each object)
self.make = make
self.model = model
self.year = year
self.speed = 0
print(f"A new {self.year} {self.make} {self.model} has been created!")
def accelerate(self, increment: int):
self.speed += increment
return f"The {self.make} {self.model} accelerates to {self.speed} km/h."
def brake(self, decrement: int):
self.speed = max(0, self.speed - decrement)
return f"The {self.make} {self.model} slows down to {self.speed} km/h."
def get_description(self):
return f"This is a {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
print(my_car.get_description())
print(my_car.accelerate(50))
print(my_car.brake(20))
print(f"My car's current speed: {my_car.speed} km/h")
print(f"n{your_car.get_description()}")
print(your_car.accelerate(70))
print(f"Your car has {your_car.wheels} wheels.") # Accessing a class attribute
```
Output example:
```
A new 2022 Toyota Camry has been created!
A new 2023 Honda Civic has been created!
This is a 2022 Toyota Camry.
The Toyota Camry accelerates to 50 km/h.
The Toyota Camry slows down to 30 km/h.
My car's current speed: 30 km/h
This is a 2023 Honda Civic.
The Honda Civic accelerates to 70 km/h.
Your car has 4 wheels.
```
**Challenge:**
Extend the `Car` class by adding a new method, for example, `honk()`, that prints a "Beep! Beep!" message along with the car's model. Then, create another `Car` object and try out your new method! 🚘
---
What is the primary purpose of the `__init__` method in a Python class?
Anonymous Quiz
0%
A) To define class-level attributes.
0%
B) To initialize a new object's attributes when it is created.
0%
C) To execute code when the class is loaded.
0%
D) To destroy an object when it goes out of scope.
Here's your Telegram post and quiz question:
---
🌟 **Day 14: Diving into Inheritance & Polymorphism!** 🚀
Today, we unlock the power of Object-Oriented Programming (OOP) to build more scalable and organized code. Inheritance allows new classes to inherit properties and methods from existing ones, promoting code reusability. Polymorphism, on the other hand, lets us treat objects of different classes in a uniform way, making our code flexible and adaptable. Get ready to master these fundamental OOP pillars! 👇
```python
# Base Class (Parent Class)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a generic sound."
# Derived Class (Child Class) - inherits from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's constructor
self.breed = breed
def speak(self): # Method Overriding (Polymorphism)
return f"{self.name} barks loudly!"
# Another Derived Class - also inherits from Animal
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self): # Method Overriding (Polymorphism)
return f"{self.name} meows softly."
# A function demonstrating Polymorphism
# It can take any object that has a 'speak' method
def animal_action(animal):
print(animal.speak())
# Creating objects
my_generic_animal = Animal("Beast")
my_dog = Dog("Buddy", "Golden Retriever")
my_cat = Cat("Whiskers", "Tabby")
# Demonstrating Polymorphism: calling animal_action with different object types
print("--- Polymorphism in action ---")
animal_action(my_generic_animal)
animal_action(my_dog)
animal_action(my_cat)
print("n--- Inheritance example ---")
print(f"{my_dog.name} is a {my_dog.breed}.")
print(f"{my_cat.name} is a {my_cat.color} cat.")
```
**Output example:**
```
--- Polymorphism in action ---
Beast makes a generic sound.
Buddy barks loudly!
Whiskers meows softly.
--- Inheritance example ---
Buddy is a Golden Retriever.
Whiskers is a Tabby cat.
```
💡 **Your Challenge:**
Create a new class called `Bird` 🐦 that also inherits from `Animal`. Give it a unique attribute (like `wingspan`) and override the `speak` method to make it chirp! Then, create an instance of your `Bird` and pass it to the `animal_action` function. Show us your creative animals! 🚀
---
---
🌟 **Day 14: Diving into Inheritance & Polymorphism!** 🚀
Today, we unlock the power of Object-Oriented Programming (OOP) to build more scalable and organized code. Inheritance allows new classes to inherit properties and methods from existing ones, promoting code reusability. Polymorphism, on the other hand, lets us treat objects of different classes in a uniform way, making our code flexible and adaptable. Get ready to master these fundamental OOP pillars! 👇
```python
# Base Class (Parent Class)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a generic sound."
# Derived Class (Child Class) - inherits from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's constructor
self.breed = breed
def speak(self): # Method Overriding (Polymorphism)
return f"{self.name} barks loudly!"
# Another Derived Class - also inherits from Animal
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def speak(self): # Method Overriding (Polymorphism)
return f"{self.name} meows softly."
# A function demonstrating Polymorphism
# It can take any object that has a 'speak' method
def animal_action(animal):
print(animal.speak())
# Creating objects
my_generic_animal = Animal("Beast")
my_dog = Dog("Buddy", "Golden Retriever")
my_cat = Cat("Whiskers", "Tabby")
# Demonstrating Polymorphism: calling animal_action with different object types
print("--- Polymorphism in action ---")
animal_action(my_generic_animal)
animal_action(my_dog)
animal_action(my_cat)
print("n--- Inheritance example ---")
print(f"{my_dog.name} is a {my_dog.breed}.")
print(f"{my_cat.name} is a {my_cat.color} cat.")
```
**Output example:**
```
--- Polymorphism in action ---
Beast makes a generic sound.
Buddy barks loudly!
Whiskers meows softly.
--- Inheritance example ---
Buddy is a Golden Retriever.
Whiskers is a Tabby cat.
```
💡 **Your Challenge:**
Create a new class called `Bird` 🐦 that also inherits from `Animal`. Give it a unique attribute (like `wingspan`) and override the `speak` method to make it chirp! Then, create an instance of your `Bird` and pass it to the `animal_action` function. Show us your creative animals! 🚀
---
✨ Day 15: Introduction to Python Libraries! ✨
Today, we're diving into the incredibly powerful `requests` library! 🌐💻 This essential tool allows your Python scripts to make HTTP requests, interact with web APIs, and fetch data from the internet with ease. Whether you're building a web scraper or integrating with an online service, `requests` is your go-to. Let's see how simple it is to get started with a basic GET request! 🚀
```python
import requests
# Make a GET request to a public API (JSONPlaceholder for example)
print("Fetching data from JSONPlaceholder (a dummy API)...")
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
# Check if the request was successful (status code 200)
if response.status_code == 200:
print(f"Status Code: {response.status_code} - Success!")
print("Response JSON:")
# .json() parses the response body as a Python dictionary/list
print(response.json())
else:
print(f"Error: Could not fetch data. Status Code: {response.status_code}")
```
Output example:
Fetching data from JSONPlaceholder (a dummy API)...
Status Code: 200 - Success!
Response JSON:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
🔗 **Your Challenge:**
Modify the code to fetch a random cat fact from the `https://catfact.ninja/fact` API. Can you print *only* the `fact` string from the JSON response? (Hint: The response will have keys like `fact` and `length`). Good luck! 😼
---
Today, we're diving into the incredibly powerful `requests` library! 🌐💻 This essential tool allows your Python scripts to make HTTP requests, interact with web APIs, and fetch data from the internet with ease. Whether you're building a web scraper or integrating with an online service, `requests` is your go-to. Let's see how simple it is to get started with a basic GET request! 🚀
```python
import requests
# Make a GET request to a public API (JSONPlaceholder for example)
print("Fetching data from JSONPlaceholder (a dummy API)...")
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
# Check if the request was successful (status code 200)
if response.status_code == 200:
print(f"Status Code: {response.status_code} - Success!")
print("Response JSON:")
# .json() parses the response body as a Python dictionary/list
print(response.json())
else:
print(f"Error: Could not fetch data. Status Code: {response.status_code}")
```
Output example:
Fetching data from JSONPlaceholder (a dummy API)...
Status Code: 200 - Success!
Response JSON:
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
🔗 **Your Challenge:**
Modify the code to fetch a random cat fact from the `https://catfact.ninja/fact` API. Can you print *only* the `fact` string from the JSON response? (Hint: The response will have keys like `fact` and `length`). Good luck! 😼
---
Which method is used to send a GET request using the `requests` library?
Anonymous Quiz
0%
requests.get()
0%
requests.fetch()
0%
requests.query()
0%
requests.retrieve()
Here's your Telegram post for the Python learning series:
---
🚀 Day 16: Working with APIs! 🌐 Ready to make your Python scripts talk to the world? Today we dive into the fascinating realm of Application Programming Interfaces (APIs)! We'll learn how to send requests, fetch data, and integrate external services into our applications using the powerful `requests` library. Get ready to unlock a universe of data! 💻🔗
Let's fetch some dummy data from an online API:
```python
import requests
# Define the API endpoint for a single post
url = "https://jsonplaceholder.typicode.com/posts/1"
try:
# Send a GET request to the API
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
# Parse the JSON response
data = response.json()
print(f"Post ID: {data['id']}")
print(f"Title: {data['title']}")
print(f"Body (first 70 chars): {data['body'][:70]}...")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
except ValueError: # Catches errors if response is not valid JSON
print(f"Response was not valid JSON: {response.text}")
```
Output example:
```
Post ID: 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body (first 70 chars): quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae...
```
💡 Small Challenge: Modify the code to fetch a list of *all* posts (e.g., from `https://jsonplaceholder.typicode.com/posts`) and print the titles of the first 3 posts. What happens if you try to access `response.json()` when the API returns an error page (HTML) instead of JSON?
---
---
🚀 Day 16: Working with APIs! 🌐 Ready to make your Python scripts talk to the world? Today we dive into the fascinating realm of Application Programming Interfaces (APIs)! We'll learn how to send requests, fetch data, and integrate external services into our applications using the powerful `requests` library. Get ready to unlock a universe of data! 💻🔗
Let's fetch some dummy data from an online API:
```python
import requests
# Define the API endpoint for a single post
url = "https://jsonplaceholder.typicode.com/posts/1"
try:
# Send a GET request to the API
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
# Parse the JSON response
data = response.json()
print(f"Post ID: {data['id']}")
print(f"Title: {data['title']}")
print(f"Body (first 70 chars): {data['body'][:70]}...")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
except ValueError: # Catches errors if response is not valid JSON
print(f"Response was not valid JSON: {response.text}")
```
Output example:
```
Post ID: 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body (first 70 chars): quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae...
```
💡 Small Challenge: Modify the code to fetch a list of *all* posts (e.g., from `https://jsonplaceholder.typicode.com/posts`) and print the titles of the first 3 posts. What happens if you try to access `response.json()` when the API returns an error page (HTML) instead of JSON?
---
Which Python library is commonly used for making HTTP requests to APIs?
Anonymous Quiz
0%
json
0%
requests
0%
urllib
100%
http.client
🚀 Day 17: Diving into JSON Data Handling! 🌐 Ever wondered how web services exchange data or how structured information is stored? JSON (JavaScript Object Notation) is your answer! Today, we'll master Python's built-in `json` module to effortlessly convert between JSON strings and Python dictionaries. This skill is crucial for working with APIs, web development, and persistent data storage. Let's make your Python scripts data-savvy! ✨
```python
import json
# Sample JSON data as a string
json_string = '''
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": ["Python", "Data Science"],
"address": {
"city": "Techville",
"zip": "12345"
}
}
'''
print("--- Parsing JSON String to Python Dictionary ---")
# Convert JSON string to Python dictionary
data_dict = json.loads(json_string)
print(f"Python Dictionary: {data_dict}")
print(f"Name: {data_dict['name']}")
print(f"First Course: {data_dict['courses'][0]}")
print("n--- Converting Python Dictionary to JSON String ---")
# Modify the dictionary
data_dict['age'] += 1
data_dict['new_field'] = 'Hello JSON!'
# Convert Python dictionary back to JSON string
# 'indent' makes the output human-readable
new_json_string = json.dumps(data_dict, indent=4)
print(f"New JSON String:n{new_json_string}")
```
Output example:
```
--- Parsing JSON String to Python Dictionary ---
Python Dictionary: {'name': 'Alice', 'age': 30, 'isStudent': False, 'courses': ['Python', 'Data Science'], 'address': {'city': 'Techville', 'zip': '12345'}}
Name: Alice
First Course: Python
--- Converting Python Dictionary to JSON String ---
New JSON String:
{
"name": "Alice",
"age": 31,
"isStudent": false,
"courses": [
"Python",
"Data Science"
],
"address": {
"city": "Techville",
"zip": "12345"
},
"new_field": "Hello JSON!"
}
```
💡 Your Challenge: Try adding another course, 'Machine Learning', to the `courses` list in `data_dict` *before* dumping it back to JSON. See how the output changes!
---
```python
import json
# Sample JSON data as a string
json_string = '''
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": ["Python", "Data Science"],
"address": {
"city": "Techville",
"zip": "12345"
}
}
'''
print("--- Parsing JSON String to Python Dictionary ---")
# Convert JSON string to Python dictionary
data_dict = json.loads(json_string)
print(f"Python Dictionary: {data_dict}")
print(f"Name: {data_dict['name']}")
print(f"First Course: {data_dict['courses'][0]}")
print("n--- Converting Python Dictionary to JSON String ---")
# Modify the dictionary
data_dict['age'] += 1
data_dict['new_field'] = 'Hello JSON!'
# Convert Python dictionary back to JSON string
# 'indent' makes the output human-readable
new_json_string = json.dumps(data_dict, indent=4)
print(f"New JSON String:n{new_json_string}")
```
Output example:
```
--- Parsing JSON String to Python Dictionary ---
Python Dictionary: {'name': 'Alice', 'age': 30, 'isStudent': False, 'courses': ['Python', 'Data Science'], 'address': {'city': 'Techville', 'zip': '12345'}}
Name: Alice
First Course: Python
--- Converting Python Dictionary to JSON String ---
New JSON String:
{
"name": "Alice",
"age": 31,
"isStudent": false,
"courses": [
"Python",
"Data Science"
],
"address": {
"city": "Techville",
"zip": "12345"
},
"new_field": "Hello JSON!"
}
```
💡 Your Challenge: Try adding another course, 'Machine Learning', to the `courses` list in `data_dict` *before* dumping it back to JSON. See how the output changes!
---
Which Python function from the `json` module is used to convert a JSON string into a Python dictionary?
Anonymous Quiz
0%
json.dumps()
0%
json.loads()
0%
json.load()
0%
json.parse()
👋 Hey Python Learners! It's Day 18 of our series, and today we're unlocking the power of Regular Expressions (RegEx)! 🚀
RegEx might seem intimidating at first, but it's an incredibly powerful tool for searching, matching, and manipulating text patterns. From validating emails to extracting specific data, RegEx is your go-to. We'll use Python's built-in `re` module. Let's dive in! 🧐
```python
import re
text = "My phone number is 123-456-7890. Call me soon! Another number: 987.654.3210. My email is example@domain.com."
# 1. Searching for the first occurrence of a pattern (a phone number)
# d{3} matches exactly 3 digits, [-.] matches a hyphen or a period
match_phone = re.search(r'd{3}[-.]d{3}[-.]d{4}', text)
if match_phone:
print(f"Found first phone number: {match_phone.group()}")
# 2. Finding all occurrences of a pattern (all sequences of digits)
# d+ matches one or more digits
all_digits = re.findall(r'd+', text)
print(f"All sequences of digits found: {all_digits}")
# 3. Finding all occurrences of a more complex pattern (all valid phone numbers)
all_phones = re.findall(r'd{3}[-.]d{3}[-.]d{4}', text)
print(f"All phone numbers found: {all_phones}")
# 4. Finding a simple word
word_match = re.search(r'email', text)
if word_match:
print(f"Found word: '{word_match.group()}'")
```
Output example:
```
Found first phone number: 123-456-7890
All sequences of digits found: ['123', '456', '7890', '987', '654', '3210']
All phone numbers found: ['123-456-7890', '987.654.3210']
Found word: 'email'
```
✨ Challenge:
Given the text: "The meeting is scheduled for 2023-10-27 at 10:30 AM."
Use `re.search` to extract *only the year* (i.e., "2023") using a regular expression! Share your code! 👇
---
RegEx might seem intimidating at first, but it's an incredibly powerful tool for searching, matching, and manipulating text patterns. From validating emails to extracting specific data, RegEx is your go-to. We'll use Python's built-in `re` module. Let's dive in! 🧐
```python
import re
text = "My phone number is 123-456-7890. Call me soon! Another number: 987.654.3210. My email is example@domain.com."
# 1. Searching for the first occurrence of a pattern (a phone number)
# d{3} matches exactly 3 digits, [-.] matches a hyphen or a period
match_phone = re.search(r'd{3}[-.]d{3}[-.]d{4}', text)
if match_phone:
print(f"Found first phone number: {match_phone.group()}")
# 2. Finding all occurrences of a pattern (all sequences of digits)
# d+ matches one or more digits
all_digits = re.findall(r'd+', text)
print(f"All sequences of digits found: {all_digits}")
# 3. Finding all occurrences of a more complex pattern (all valid phone numbers)
all_phones = re.findall(r'd{3}[-.]d{3}[-.]d{4}', text)
print(f"All phone numbers found: {all_phones}")
# 4. Finding a simple word
word_match = re.search(r'email', text)
if word_match:
print(f"Found word: '{word_match.group()}'")
```
Output example:
```
Found first phone number: 123-456-7890
All sequences of digits found: ['123', '456', '7890', '987', '654', '3210']
All phone numbers found: ['123-456-7890', '987.654.3210']
Found word: 'email'
```
✨ Challenge:
Given the text: "The meeting is scheduled for 2023-10-27 at 10:30 AM."
Use `re.search` to extract *only the year* (i.e., "2023") using a regular expression! Share your code! 👇
---
In regular expressions (RegEx), what does the pattern `\d` typically match?
Anonymous Quiz
0%
Any character
0%
Any whitespace character
0%
Any digit (0-9)
0%
Any non-digit character
🎉 **Day 19: Virtual Environments!** 🎉
Ever found yourself in "dependency hell" where one project's requirements clash with another's? 🤯 Python virtual environments are your ultimate lifesaver! They create isolated spaces for each project, ensuring that dependencies for one don't interfere with another. Today, we'll master `venv` to keep your projects clean, consistent, and conflict-free. Get ready to streamline your workflow like a pro! 🐍✨📦
---
```python
# 1. Create a virtual environment named 'myproject_env'
# (Run this command in your project's root directory)
python3 -m venv myproject_env
# 2. Activate the virtual environment
# On Linux/macOS:
source myproject_env/bin/activate
# On Windows (Command Prompt):
# myproject_envScriptsactivate.bat
# On Windows (PowerShell):
# myproject_envScriptsActivate.ps1
# 3. Once activated, your terminal prompt will show the environment name.
# Now, any package you install with 'pip' will be confined to THIS environment.
# (myproject_env) pip install requests
# 4. When you're done working in the environment, deactivate it:
# (myproject_env) deactivate
```
---
Output example:
```
# After running 'python3 -m venv myproject_env':
# (No direct output, creates the directory)
# After running 'source myproject_env/bin/activate':
(myproject_env) user@host:~/your_project$
# After running '(myproject_env) pip install requests':
(myproject_env) user@host:~/your_project$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 KB 1.1 MB/s eta 0:00:00
... (other dependency installations)
Successfully installed charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
# After running '(myproject_env) deactivate':
user@host:~/your_project$
```
---
🚀 **Your Challenge Today:**
1. Create a new directory for a project (e.g., `my_flask_app`).
2. Navigate into that directory.
3. Create a virtual environment called `flask_env` inside it.
4. Activate `flask_env`.
5. Install the `flask` library (`pip install flask`) within this environment.
6. Verify that `flask` is indeed installed by running `pip list`.
7. Deactivate the environment.
Share your success! 👇
---
Ever found yourself in "dependency hell" where one project's requirements clash with another's? 🤯 Python virtual environments are your ultimate lifesaver! They create isolated spaces for each project, ensuring that dependencies for one don't interfere with another. Today, we'll master `venv` to keep your projects clean, consistent, and conflict-free. Get ready to streamline your workflow like a pro! 🐍✨📦
---
```python
# 1. Create a virtual environment named 'myproject_env'
# (Run this command in your project's root directory)
python3 -m venv myproject_env
# 2. Activate the virtual environment
# On Linux/macOS:
source myproject_env/bin/activate
# On Windows (Command Prompt):
# myproject_envScriptsactivate.bat
# On Windows (PowerShell):
# myproject_envScriptsActivate.ps1
# 3. Once activated, your terminal prompt will show the environment name.
# Now, any package you install with 'pip' will be confined to THIS environment.
# (myproject_env) pip install requests
# 4. When you're done working in the environment, deactivate it:
# (myproject_env) deactivate
```
---
Output example:
```
# After running 'python3 -m venv myproject_env':
# (No direct output, creates the directory)
# After running 'source myproject_env/bin/activate':
(myproject_env) user@host:~/your_project$
# After running '(myproject_env) pip install requests':
(myproject_env) user@host:~/your_project$ pip install requests
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.6/62.6 KB 1.1 MB/s eta 0:00:00
... (other dependency installations)
Successfully installed charset-normalizer-3.3.2 idna-3.6 requests-2.31.0 urllib3-2.1.0
# After running '(myproject_env) deactivate':
user@host:~/your_project$
```
---
🚀 **Your Challenge Today:**
1. Create a new directory for a project (e.g., `my_flask_app`).
2. Navigate into that directory.
3. Create a virtual environment called `flask_env` inside it.
4. Activate `flask_env`.
5. Install the `flask` library (`pip install flask`) within this environment.
6. Verify that `flask` is indeed installed by running `pip list`.
7. Deactivate the environment.
Share your success! 👇
---
What is the primary benefit of using a Python virtual environment?
Anonymous Quiz
50%
A) To speed up Python code execution.
50%
B) To create isolated environments for project-specific dependencies.
0%
C) To compile Python scripts into executable files.
0%
D) To simplify debugging of Python applications.