๐ Day 28: Diving into Asynchronous Programming with `asyncio`! โณ
Today, we're unlocking the power of non-blocking I/O with Python's `asyncio` library! ๐ง Ever wanted your program to do multiple things without waiting for each one to finish? That's what `asyncio` is for! It allows concurrent execution of operations, making your applications more responsive and efficient, especially for I/O-bound tasks like network requests or reading files. Get ready to `async` and `await` your way to faster Python code! ๐ฅ
```python
import asyncio
import time
# An asynchronous function simulating an I/O operation
async def fetch_data(item_id, delay):
print(f"[{time.strftime('%H:%M:%S')}] Fetching data for item {item_id}...")
await asyncio.sleep(delay) # Simulate a non-blocking delay
print(f"[{time.strftime('%H:%M:%S')}] Data for item {item_id} fetched after {delay}s.")
return f"Item {item_id} data"
# The main asynchronous function to orchestrate tasks
async def main():
print(f"[{time.strftime('%H:%M:%S')}] Starting main async operations.")
# Run multiple async tasks concurrently
# asyncio.gather waits for all specified awaitables to complete.
results = await asyncio.gather(
fetch_data("A", 3),
fetch_data("B", 1),
fetch_data("C", 2)
)
print(f"[{time.strftime('%H:%M:%S')}] All data fetching complete!")
print(f"Final results: {results}")
if __name__ == "__main__":
# asyncio.run() executes the top-level entry point and manages the event loop.
asyncio.run(main())
```
Output example:
```
[HH:MM:SS] Starting main async operations.
[HH:MM:SS] Fetching data for item A...
[HH:MM:SS] Fetching data for item B...
[HH:MM:SS] Fetching data for item C...
[HH:MM:SS] Data for item B fetched after 1s.
[HH:MM:SS] Data for item C fetched after 2s.
[HH:MM:SS] Data for item A fetched after 3s.
[HH:MM:SS] All data fetching complete!
Final results: ['Item A data', 'Item B data', 'Item C data']
```
*(Note: `HH:MM:SS` will reflect the actual execution time)*
### Small challenge:
Modify the `main` function to create a new task using `asyncio.create_task()` for fetching data for "D" with a 4-second delay, instead of adding it to `asyncio.gather`. How would you await its completion along with the `gather` call? Hint: You might need another `await`! ๐ก
---
Today, we're unlocking the power of non-blocking I/O with Python's `asyncio` library! ๐ง Ever wanted your program to do multiple things without waiting for each one to finish? That's what `asyncio` is for! It allows concurrent execution of operations, making your applications more responsive and efficient, especially for I/O-bound tasks like network requests or reading files. Get ready to `async` and `await` your way to faster Python code! ๐ฅ
```python
import asyncio
import time
# An asynchronous function simulating an I/O operation
async def fetch_data(item_id, delay):
print(f"[{time.strftime('%H:%M:%S')}] Fetching data for item {item_id}...")
await asyncio.sleep(delay) # Simulate a non-blocking delay
print(f"[{time.strftime('%H:%M:%S')}] Data for item {item_id} fetched after {delay}s.")
return f"Item {item_id} data"
# The main asynchronous function to orchestrate tasks
async def main():
print(f"[{time.strftime('%H:%M:%S')}] Starting main async operations.")
# Run multiple async tasks concurrently
# asyncio.gather waits for all specified awaitables to complete.
results = await asyncio.gather(
fetch_data("A", 3),
fetch_data("B", 1),
fetch_data("C", 2)
)
print(f"[{time.strftime('%H:%M:%S')}] All data fetching complete!")
print(f"Final results: {results}")
if __name__ == "__main__":
# asyncio.run() executes the top-level entry point and manages the event loop.
asyncio.run(main())
```
Output example:
```
[HH:MM:SS] Starting main async operations.
[HH:MM:SS] Fetching data for item A...
[HH:MM:SS] Fetching data for item B...
[HH:MM:SS] Fetching data for item C...
[HH:MM:SS] Data for item B fetched after 1s.
[HH:MM:SS] Data for item C fetched after 2s.
[HH:MM:SS] Data for item A fetched after 3s.
[HH:MM:SS] All data fetching complete!
Final results: ['Item A data', 'Item B data', 'Item C data']
```
*(Note: `HH:MM:SS` will reflect the actual execution time)*
### Small challenge:
Modify the `main` function to create a new task using `asyncio.create_task()` for fetching data for "D" with a 4-second delay, instead of adding it to `asyncio.gather`. How would you await its completion along with the `gather` call? Hint: You might need another `await`! ๐ก
---
Here's your Telegram post for Day 29!
---
๐ฅณ Day 29: Database Dive! ๐ฅณ
Ready to make your Python apps store and retrieve data persistently? Today, we're diving into basic database interaction using **SQLite**! ๐๏ธ It's a lightweight, serverless database perfect for learning and many small-to-medium projects.
We'll learn how to:
โ Connect to a database
โ Create a table
โ Insert new records
โ Query existing data
Let's make our data stick! ๐พ
```python
import sqlite3
def main():
# 1. Connect to a SQLite database (or create it if it doesn't exist)
# Using 'with' statement ensures the connection is properly closed even if errors occur.
with sqlite3.connect('my_python_data.db') as conn:
cursor = conn.cursor()
# 2. Create a table
# IF NOT EXISTS prevents an error if the table already exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
print("Table 'users' ensured to exist.")
# 3. Insert data
# Note: Running this multiple times will add duplicate users.
# For a real application, you'd add logic to check for existing data first.
new_users = [
('Eve', 28),
('Frank', 42),
('Grace', 31)
]
print(f"Attempting to insert {len(new_users)} new users...")
try:
# The '?' are placeholders for safe parameter substitution
cursor.executemany("INSERT INTO users (name, age) VALUES (?, ?)", new_users)
# 4. Commit changes (save them permanently to the database file)
conn.commit()
print("New users inserted and changes committed.")
except sqlite3.IntegrityError as e:
print(f"Error inserting users: {e}. Perhaps a unique constraint was violated.")
conn.rollback() # Rollback changes if an error occurred
# 5. Query data
print("nAll users currently in the database:")
# Select specific columns for clarity and order by ID
cursor.execute("SELECT id, name, age FROM users ORDER BY id ASC")
for row in cursor.fetchall(): # fetchall() retrieves all results
print(row)
print("nDatabase operations completed. You can find 'my_python_data.db' in your directory!")
if __name__ == "__main__":
main()
```
Output example:
```
Table 'users' ensured to exist.
Attempting to insert 3 new users...
New users inserted and changes committed.
All users currently in the database:
(1, 'Eve', 28)
(2, 'Frank', 42)
(3, 'Grace', 31)
Database operations completed. You can find 'my_python_data.db' in your directory!
```
*(Note: If you run the script multiple times, the 'id' numbers will continue to increment, and you'll see duplicate 'Eve', 'Frank', 'Grace' entries unless you add logic to prevent it.)*
๐ก **Challenge:**
Modify the script to:
1. Add another new user with a unique name and age.
2. Update the age of 'Eve' to 30.
3. Delete the user 'Frank' from the database.
Remember to `conn.commit()` your changes after `INSERT`, `UPDATE`, and `DELETE`! โจ
---
---
๐ฅณ Day 29: Database Dive! ๐ฅณ
Ready to make your Python apps store and retrieve data persistently? Today, we're diving into basic database interaction using **SQLite**! ๐๏ธ It's a lightweight, serverless database perfect for learning and many small-to-medium projects.
We'll learn how to:
โ Connect to a database
โ Create a table
โ Insert new records
โ Query existing data
Let's make our data stick! ๐พ
```python
import sqlite3
def main():
# 1. Connect to a SQLite database (or create it if it doesn't exist)
# Using 'with' statement ensures the connection is properly closed even if errors occur.
with sqlite3.connect('my_python_data.db') as conn:
cursor = conn.cursor()
# 2. Create a table
# IF NOT EXISTS prevents an error if the table already exists
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
print("Table 'users' ensured to exist.")
# 3. Insert data
# Note: Running this multiple times will add duplicate users.
# For a real application, you'd add logic to check for existing data first.
new_users = [
('Eve', 28),
('Frank', 42),
('Grace', 31)
]
print(f"Attempting to insert {len(new_users)} new users...")
try:
# The '?' are placeholders for safe parameter substitution
cursor.executemany("INSERT INTO users (name, age) VALUES (?, ?)", new_users)
# 4. Commit changes (save them permanently to the database file)
conn.commit()
print("New users inserted and changes committed.")
except sqlite3.IntegrityError as e:
print(f"Error inserting users: {e}. Perhaps a unique constraint was violated.")
conn.rollback() # Rollback changes if an error occurred
# 5. Query data
print("nAll users currently in the database:")
# Select specific columns for clarity and order by ID
cursor.execute("SELECT id, name, age FROM users ORDER BY id ASC")
for row in cursor.fetchall(): # fetchall() retrieves all results
print(row)
print("nDatabase operations completed. You can find 'my_python_data.db' in your directory!")
if __name__ == "__main__":
main()
```
Output example:
```
Table 'users' ensured to exist.
Attempting to insert 3 new users...
New users inserted and changes committed.
All users currently in the database:
(1, 'Eve', 28)
(2, 'Frank', 42)
(3, 'Grace', 31)
Database operations completed. You can find 'my_python_data.db' in your directory!
```
*(Note: If you run the script multiple times, the 'id' numbers will continue to increment, and you'll see duplicate 'Eve', 'Frank', 'Grace' entries unless you add logic to prevent it.)*
๐ก **Challenge:**
Modify the script to:
1. Add another new user with a unique name and age.
2. Update the age of 'Eve' to 30.
3. Delete the user 'Frank' from the database.
Remember to `conn.commit()` your changes after `INSERT`, `UPDATE`, and `DELETE`! โจ
---
In Python's `sqlite3` module, what is the primary purpose of calling `conn.commit()` after executing SQL commands like `INSERT` or `UPDATE`?
Anonymous Quiz
0%
To save the changes permanently to the database file.
0%
To close the database connection safely.
0%
To rollback any changes made since the last commit.
0%
To fetch all results from a `SELECT` query.
๐ฅณ **Day 30: Final Project Idea and Review!** ๐
We've reached a significant milestone, Pythonistas! ๐ Today isn't about learning complex new syntax, but about *applying* everything you've absorbed over the past month. We'll explore ideas for your final project and crucial steps for reviewing your progress. It's time to consolidate your knowledge, think creatively, and prepare to build something truly yours! Let's get ready to turn concepts into code! โจ
```python
import random
def get_project_idea_and_review_prompt():
"""
Suggests a project type and provides prompts for self-review.
"""
project_types = [
"a command-line utility (e.g., a file organizer)",
"a simple web application (using Flask/Django basics for a 'Hello World' app)",
"a data analysis script (e.g., parsing a CSV file)",
"a text-based game (e.g., 'Guess the Number')",
"an automation script (e.g., renaming multiple files)"
]
suggested_type = random.choice(project_types)
print(f"๐ Your Final Project Idea Suggestion: Build {suggested_type}!")
print("n--- Project Planning & Review Prompts ---")
print("1. What's the *core problem* or *functionality* your project aims to provide?")
print("2. List 3-5 Python concepts/modules from this series you'll definitely use.")
print("3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?")
print("4. What's one *minimum viable feature* you'll implement first?")
print("5. What potential challenges do you foresee and how might you tackle them?")
print("nGood luck building your masterpiece! You've got this! ๐ช")
if __name__ == "__main__":
get_project_idea_and_review_prompt()
```
Output example:
```
๐ Your Final Project Idea Suggestion: Build a data analysis script (e.g., parsing a CSV file)!
--- Project Planning & Review Prompts ---
1. What's the *core problem* or *functionality* your project aims to provide?
2. List 3-5 Python concepts/modules from this series you'll definitely use.
3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?
4. What's one *minimum viable feature* you'll implement first?
5. What potential challenges do you foresee and how might you tackle them?
Good luck building your masterpiece! You've got this! ๐ช
```
**Small Challenge:**
Your Challenge: Modify the `get_project_idea_and_review_prompt` function to *also* suggest 2-3 specific Python modules (e.g., `os`, `csv`, `requests`, `datetime`) that would be particularly useful for the randomly chosen project type. How would you map modules to project types? ๐ค
---
We've reached a significant milestone, Pythonistas! ๐ Today isn't about learning complex new syntax, but about *applying* everything you've absorbed over the past month. We'll explore ideas for your final project and crucial steps for reviewing your progress. It's time to consolidate your knowledge, think creatively, and prepare to build something truly yours! Let's get ready to turn concepts into code! โจ
```python
import random
def get_project_idea_and_review_prompt():
"""
Suggests a project type and provides prompts for self-review.
"""
project_types = [
"a command-line utility (e.g., a file organizer)",
"a simple web application (using Flask/Django basics for a 'Hello World' app)",
"a data analysis script (e.g., parsing a CSV file)",
"a text-based game (e.g., 'Guess the Number')",
"an automation script (e.g., renaming multiple files)"
]
suggested_type = random.choice(project_types)
print(f"๐ Your Final Project Idea Suggestion: Build {suggested_type}!")
print("n--- Project Planning & Review Prompts ---")
print("1. What's the *core problem* or *functionality* your project aims to provide?")
print("2. List 3-5 Python concepts/modules from this series you'll definitely use.")
print("3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?")
print("4. What's one *minimum viable feature* you'll implement first?")
print("5. What potential challenges do you foresee and how might you tackle them?")
print("nGood luck building your masterpiece! You've got this! ๐ช")
if __name__ == "__main__":
get_project_idea_and_review_prompt()
```
Output example:
```
๐ Your Final Project Idea Suggestion: Build a data analysis script (e.g., parsing a CSV file)!
--- Project Planning & Review Prompts ---
1. What's the *core problem* or *functionality* your project aims to provide?
2. List 3-5 Python concepts/modules from this series you'll definitely use.
3. How will you break down this project into smaller, manageable tasks (e.g., input, processing, output)?
4. What's one *minimum viable feature* you'll implement first?
5. What potential challenges do you foresee and how might you tackle them?
Good luck building your masterpiece! You've got this! ๐ช
```
**Small Challenge:**
Your Challenge: Modify the `get_project_idea_and_review_prompt` function to *also* suggest 2-3 specific Python modules (e.g., `os`, `csv`, `requests`, `datetime`) that would be particularly useful for the randomly chosen project type. How would you map modules to project types? ๐ค
---
What is generally considered the most critical first step when embarking on a new programming project?
Anonymous Quiz
0%
Writing the user interface code immediately
0%
Defining the project's scope, requirements, and desired outcomes
0%
Choosing the most popular programming language without prior research
0%
Starting to code the most complex algorithm first
๐ Day 31: Ready to elevate your Python architecture? Today, we're diving into **Architecting with Algebraic Data Types (ADTs)** and leveraging Python's powerful `match/case` statement for robust state machines! ๐ฏ Discover how to model complex domains with unparalleled clarity and reduce bugs by making invalid states impossible. This paradigm shift will transform how you handle control flow and state management, leading to cleaner, more maintainable code. Let's build truly robust systems! โจ
```python
from dataclasses import dataclass
from typing import Union
# Simulate Algebraic Data Types (ADTs) using dataclasses
# Each class represents a distinct state (a "variant" of the sum type)
@dataclass(frozen=True)
class Red:
duration: int = 30 # seconds
@dataclass(frozen=True)
class Yellow:
duration: int = 5
@dataclass(frozen=True)
class Green:
duration: int = 45
# Our "ADT" for TrafficLightState is effectively Red | Yellow | Green
TrafficLightState = Union[Red, Yellow, Green] # Using Union for type hinting pre-Python 3.10, or | for 3.10+
def transition_light(current_state: TrafficLightState, action: str) -> TrafficLightState:
"""
Transitions the traffic light state based on the current state and action.
Uses Python's match/case for elegant state machine logic.
"""
if action == "NEXT":
match current_state:
case Red(duration):
print(f"๐ฆ Currently Red for {duration}s. Transitioning to Yellow.")
return Yellow()
case Yellow(duration):
print(f"๐ฆ Currently Yellow for {duration}s. Transitioning to Green.")
return Green()
case Green(duration):
print(f"๐ฆ Currently Green for {duration}s. Transitioning to Red.")
return Red()
case _: # Catch-all for unhandled states (should ideally be unreachable)
raise ValueError(f"Unknown traffic light state encountered: {current_state}")
else:
raise ValueError(f"Unknown action: {action}")
# Initial state
current_light = Red()
print(f"Initial State: {current_light}")
# Simulate transitions
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT") # Go back to Yellow
print(f"New State: {current_light}")
```
Output example:
```
Initial State: Red(duration=30)
๐ฆ Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)
๐ฆ Currently Yellow for 5s. Transitioning to Green.
New State: Green(duration=45)
๐ฆ Currently Green for 45s. Transitioning to Red.
New State: Red(duration=30)
๐ฆ Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)
```
๐ก **Your Challenge:** Extend our `TrafficLightState`! Add a `FlashingYellow` state that can be reached from `Yellow` (perhaps on a specific `action` like "FLASH") and then transitions back to `Yellow` or `Red` depending on your logic. How would you update the `transition_light` function using `match/case`?
---
```python
from dataclasses import dataclass
from typing import Union
# Simulate Algebraic Data Types (ADTs) using dataclasses
# Each class represents a distinct state (a "variant" of the sum type)
@dataclass(frozen=True)
class Red:
duration: int = 30 # seconds
@dataclass(frozen=True)
class Yellow:
duration: int = 5
@dataclass(frozen=True)
class Green:
duration: int = 45
# Our "ADT" for TrafficLightState is effectively Red | Yellow | Green
TrafficLightState = Union[Red, Yellow, Green] # Using Union for type hinting pre-Python 3.10, or | for 3.10+
def transition_light(current_state: TrafficLightState, action: str) -> TrafficLightState:
"""
Transitions the traffic light state based on the current state and action.
Uses Python's match/case for elegant state machine logic.
"""
if action == "NEXT":
match current_state:
case Red(duration):
print(f"๐ฆ Currently Red for {duration}s. Transitioning to Yellow.")
return Yellow()
case Yellow(duration):
print(f"๐ฆ Currently Yellow for {duration}s. Transitioning to Green.")
return Green()
case Green(duration):
print(f"๐ฆ Currently Green for {duration}s. Transitioning to Red.")
return Red()
case _: # Catch-all for unhandled states (should ideally be unreachable)
raise ValueError(f"Unknown traffic light state encountered: {current_state}")
else:
raise ValueError(f"Unknown action: {action}")
# Initial state
current_light = Red()
print(f"Initial State: {current_light}")
# Simulate transitions
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT")
print(f"New State: {current_light}n")
current_light = transition_light(current_light, "NEXT") # Go back to Yellow
print(f"New State: {current_light}")
```
Output example:
```
Initial State: Red(duration=30)
๐ฆ Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)
๐ฆ Currently Yellow for 5s. Transitioning to Green.
New State: Green(duration=45)
๐ฆ Currently Green for 45s. Transitioning to Red.
New State: Red(duration=30)
๐ฆ Currently Red for 30s. Transitioning to Yellow.
New State: Yellow(duration=5)
```
๐ก **Your Challenge:** Extend our `TrafficLightState`! Add a `FlashingYellow` state that can be reached from `Yellow` (perhaps on a specific `action` like "FLASH") and then transitions back to `Yellow` or `Red` depending on your logic. How would you update the `transition_light` function using `match/case`?
---
๐ Day 32 Alert! Get ready to dive deep into Python's core! Ever wondered how Python *really* executes your code? This session, "The Bytecode Whisperer," unpacks the Abstract Syntax Tree (AST) โ the hidden blueprint of your programs. We'll learn to dissect it, manipulate it, and even rewrite it on the fly. Unleash truly dynamic behavior and explore extreme optimization techniques that go beyond conventional Python. Prepare to wield immense power! โจ
```python
import ast
# Original Python code as a string
original_code = """
def greet():
message = "Hello, Pythonista!"
print(message)
greet()
"""
# 1. Parse the original code into an AST
tree = ast.parse(original_code)
# 2. Define a custom AST transformer
class GreetTransformer(ast.NodeTransformer):
def visit_Constant(self, node):
# Change string literals within the AST
if isinstance(node.value, str) and node.value == "Hello, Pythonista!":
return ast.Constant(value="Bonjour, cher dรฉveloppeur!")
return node
def visit_FunctionDef(self, node):
# Inject a print statement at the beginning of the function body
if node.name == "greet":
new_print_stmt = ast.Expr(
value=ast.Call(
func=ast.Name(id='print', ctx=ast.Load()),
args=[ast.Constant(value="--- AST Magic Ahead! ---")],
keywords=[]
)
)
node.body.insert(0, new_print_stmt) # Insert at the beginning
return self.generic_visit(node) # Ensure other nodes are visited
# 3. Transform the AST
transformer = GreetTransformer()
new_tree = transformer.visit(tree)
# 4. Fix missing line numbers and other metadata in the new tree
ast.fix_missing_locations(new_tree)
# 5. Compile the modified AST
compiled_code = compile(new_tree, '<string>', 'exec')
# 6. Execute the modified code
print("--- Executing AST-Transformed Code ---")
exec(compiled_code)
```
Output example:
```
--- Executing AST-Transformed Code ---
--- AST Magic Ahead! ---
Bonjour, cher dรฉveloppeur!
```
Challenge accepted! ๐ Can you modify the `GreetTransformer` to also inject another `print` statement at the *end* of the `greet` function's body, saying '--- AST Magic Complete! ---'?
```python
import ast
# Original Python code as a string
original_code = """
def greet():
message = "Hello, Pythonista!"
print(message)
greet()
"""
# 1. Parse the original code into an AST
tree = ast.parse(original_code)
# 2. Define a custom AST transformer
class GreetTransformer(ast.NodeTransformer):
def visit_Constant(self, node):
# Change string literals within the AST
if isinstance(node.value, str) and node.value == "Hello, Pythonista!":
return ast.Constant(value="Bonjour, cher dรฉveloppeur!")
return node
def visit_FunctionDef(self, node):
# Inject a print statement at the beginning of the function body
if node.name == "greet":
new_print_stmt = ast.Expr(
value=ast.Call(
func=ast.Name(id='print', ctx=ast.Load()),
args=[ast.Constant(value="--- AST Magic Ahead! ---")],
keywords=[]
)
)
node.body.insert(0, new_print_stmt) # Insert at the beginning
return self.generic_visit(node) # Ensure other nodes are visited
# 3. Transform the AST
transformer = GreetTransformer()
new_tree = transformer.visit(tree)
# 4. Fix missing line numbers and other metadata in the new tree
ast.fix_missing_locations(new_tree)
# 5. Compile the modified AST
compiled_code = compile(new_tree, '<string>', 'exec')
# 6. Execute the modified code
print("--- Executing AST-Transformed Code ---")
exec(compiled_code)
```
Output example:
```
--- Executing AST-Transformed Code ---
--- AST Magic Ahead! ---
Bonjour, cher dรฉveloppeur!
```
Challenge accepted! ๐ Can you modify the `GreetTransformer` to also inject another `print` statement at the *end* of the `greet` function's body, saying '--- AST Magic Complete! ---'?
Which of the following modules is primarily used for parsing Python source code into an Abstract Syntax Tree (AST)?
Anonymous Quiz
0%
dis
0%
ast
0%
inspect
0%
codecs
๐ Welcome to Day 1 of our Python learning journey! ๐ Today, we're taking our first step into the exciting world of programming with Python. We'll start with the absolute classic: "Hello, World!" This simple program is a tradition for every new language learner and helps you verify your setup is ready to go. Get ready to write your first line of code! ๐
---
```python
print("Hello, World!")
```
---
Output example:
Hello, World!
---
Small challenge:
Try modifying the code to print your name or a different greeting instead of "Hello, World!". For example, `print("Hello, [Your Name]!")` What happens if you forget the quotation marks around your text? ๐ค
---
---
```python
print("Hello, World!")
```
---
Output example:
Hello, World!
---
Small challenge:
Try modifying the code to print your name or a different greeting instead of "Hello, World!". For example, `print("Hello, [Your Name]!")` What happens if you forget the quotation marks around your text? ๐ค
---
What is the primary purpose of the `print()` function in Python?
Anonymous Quiz
0%
To perform mathematical calculations
50%
To display output on the console
0%
To define new variables
50%
To read input from the user
๐๐ Day 2: Variables and Data Types! ๐ก
Ready to store some information? Today, we're diving into *variables* โ your Python program's memory cells! Think of them as labeled containers where you can store different kinds of data. We'll also explore *data types*, which tell Python what kind of information is inside your container (like text, whole numbers, decimals, or true/false values). Let's get hands-on! ๐
---
### Python Code:
```python
# Storing information in variables
user_name = "Anna" # String (text)
user_age = 25 # Integer (whole number)
user_height = 1.68 # Float (decimal number)
is_active_user = True # Boolean (True or False)
print(f"Hello, {user_name}!")
print(f"You are {user_age} years old.")
print(f"Your height is {user_height} meters.")
print(f"Active user status: {is_active_user}")
# Let's check their types!
print(f"nType of user_name: {type(user_name)}")
print(f"Type of user_age: {type(user_age)}")
print(f"Type of user_height: {type(user_height)}")
print(f"Type of is_active_user: {type(is_active_user)}")
# Variables can be reassigned!
user_age = user_age + 1 # Happy birthday!
print(f"nAfter birthday, user_age is: {user_age}")
```
---
### Output example:
```
Hello, Anna!
You are 25 years old.
Your height is 1.68 meters.
Active user status: True
Type of user_name: <class 'str'>
Type of user_age: <class 'int'>
Type of user_height: <class 'float'>
Type of is_active_user: <class 'bool'>
After birthday, user_age is: 26
```
---
### Small Challenge: ๐ง
Create two variables: `product_name` (a string) and `product_price` (a float). Then, print a sentence like: "The [product_name] costs $[product_price]." Don't forget to use f-strings for easy formatting! โจ
---
Keep coding and see you for Day 3! Happy learning! ๐จโ๐ป๐ฉโ๐ป
---
### Quiz Question:
Ready to store some information? Today, we're diving into *variables* โ your Python program's memory cells! Think of them as labeled containers where you can store different kinds of data. We'll also explore *data types*, which tell Python what kind of information is inside your container (like text, whole numbers, decimals, or true/false values). Let's get hands-on! ๐
---
### Python Code:
```python
# Storing information in variables
user_name = "Anna" # String (text)
user_age = 25 # Integer (whole number)
user_height = 1.68 # Float (decimal number)
is_active_user = True # Boolean (True or False)
print(f"Hello, {user_name}!")
print(f"You are {user_age} years old.")
print(f"Your height is {user_height} meters.")
print(f"Active user status: {is_active_user}")
# Let's check their types!
print(f"nType of user_name: {type(user_name)}")
print(f"Type of user_age: {type(user_age)}")
print(f"Type of user_height: {type(user_height)}")
print(f"Type of is_active_user: {type(is_active_user)}")
# Variables can be reassigned!
user_age = user_age + 1 # Happy birthday!
print(f"nAfter birthday, user_age is: {user_age}")
```
---
### Output example:
```
Hello, Anna!
You are 25 years old.
Your height is 1.68 meters.
Active user status: True
Type of user_name: <class 'str'>
Type of user_age: <class 'int'>
Type of user_height: <class 'float'>
Type of is_active_user: <class 'bool'>
After birthday, user_age is: 26
```
---
### Small Challenge: ๐ง
Create two variables: `product_name` (a string) and `product_price` (a float). Then, print a sentence like: "The [product_name] costs $[product_price]." Don't forget to use f-strings for easy formatting! โจ
---
Keep coding and see you for Day 3! Happy learning! ๐จโ๐ป๐ฉโ๐ป
---
### Quiz Question:
Which of the following is NOT a valid variable name in Python?
Anonymous Quiz
0%
my_variable
50%
_data
50%
1st_number
0%
userAge
๐ Day 3: Mastering Python Operators! ๐ป
Today, we're diving into the essential world of **operators** in Python! These special symbols perform operations on values and variables, allowing you to manipulate data, make comparisons, and control program flow. From basic arithmetic to logical conditions, understanding operators is fundamental to writing effective and dynamic Python code. Get ready to put them into action! โจ
```python
# --- Python Operators Example ---
# Arithmetic Operators
a = 15
b = 4
print(f"Addition (a + b): {a + b}")
print(f"Subtraction (a - b): {a - b}")
print(f"Multiplication (a * b): {a * b}")
print(f"Division (a / b): {a / b}") # Float division
print(f"Floor Division (a // b): {a // b}") # Integer division (rounds down)
print(f"Modulus (a % b): {a % b}") # Remainder
print(f"Exponentiation (a ** b): {a ** b}") # a to the power of b
# Assignment Operators
x = 10
x += 5 # Equivalent to x = x + 5
print(f"x after x += 5: {x}")
# Comparison Operators
print(f"Is a equal to b? (a == b): {a == b}")
print(f"Is a greater than b? (a > b): {a > b}")
print(f"Is a not equal to 15? (a != 15): {a != 15}")
# Logical Operators
is_logged_in = True
has_permission = False
print(f"Can access resource? (is_logged_in and has_permission): {is_logged_in and has_permission}")
print(f"Is user active? (is_logged_in or has_permission): {is_logged_in or has_permission}")
print(f"Is not logged in? (not is_logged_in): {not is_logged_in}")
```
Output example:
Addition (a + b): 19
Subtraction (a - b): 11
Multiplication (a * b): 60
Division (a / b): 3.75
Floor Division (a // b): 3
Modulus (a % b): 3
Exponentiation (a ** b): 50625
x after x += 5: 15
Is a equal to b? (a == b): False
Is a greater than b? (a > b): True
Is a not equal to 15? (a != 15): False
Can access resource? (is_logged_in and has_permission): False
Is user active? (is_logged_in or has_permission): True
Is not logged in? (not is_logged_in): False
---
๐ก **Small Challenge:**
Can you write a Python expression using the logical `and` operator that evaluates to `True` only if a variable `age` is between 18 and 65 (inclusive)? Share your solution!
---
Today, we're diving into the essential world of **operators** in Python! These special symbols perform operations on values and variables, allowing you to manipulate data, make comparisons, and control program flow. From basic arithmetic to logical conditions, understanding operators is fundamental to writing effective and dynamic Python code. Get ready to put them into action! โจ
```python
# --- Python Operators Example ---
# Arithmetic Operators
a = 15
b = 4
print(f"Addition (a + b): {a + b}")
print(f"Subtraction (a - b): {a - b}")
print(f"Multiplication (a * b): {a * b}")
print(f"Division (a / b): {a / b}") # Float division
print(f"Floor Division (a // b): {a // b}") # Integer division (rounds down)
print(f"Modulus (a % b): {a % b}") # Remainder
print(f"Exponentiation (a ** b): {a ** b}") # a to the power of b
# Assignment Operators
x = 10
x += 5 # Equivalent to x = x + 5
print(f"x after x += 5: {x}")
# Comparison Operators
print(f"Is a equal to b? (a == b): {a == b}")
print(f"Is a greater than b? (a > b): {a > b}")
print(f"Is a not equal to 15? (a != 15): {a != 15}")
# Logical Operators
is_logged_in = True
has_permission = False
print(f"Can access resource? (is_logged_in and has_permission): {is_logged_in and has_permission}")
print(f"Is user active? (is_logged_in or has_permission): {is_logged_in or has_permission}")
print(f"Is not logged in? (not is_logged_in): {not is_logged_in}")
```
Output example:
Addition (a + b): 19
Subtraction (a - b): 11
Multiplication (a * b): 60
Division (a / b): 3.75
Floor Division (a // b): 3
Modulus (a % b): 3
Exponentiation (a ** b): 50625
x after x += 5: 15
Is a equal to b? (a == b): False
Is a greater than b? (a > b): True
Is a not equal to 15? (a != 15): False
Can access resource? (is_logged_in and has_permission): False
Is user active? (is_logged_in or has_permission): True
Is not logged in? (not is_logged_in): False
---
๐ก **Small Challenge:**
Can you write a Python expression using the logical `and` operator that evaluates to `True` only if a variable `age` is between 18 and 65 (inclusive)? Share your solution!
---