1/9
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")This code iterates through a list of names. For each name in the list, it prints a greeting.
Key Takeaway: The for loop repeats an action for every item in a sequence. The f"..." is an f-string, which inserts the value of name directly into the text.
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers if n % 2 == 0]This code creates a new list called squares. It takes each number (n) from the numbers list, checks if it is even (n % 2 == 0), and if so, squares it (n**2). The resulting list will be [4, 16].
Key Takeaway: List comprehensions are a compact way to filter and transform lists in a single line
config = {"timeout": 30, "retry": True}
timeout_value = config.get("timeout", 60)
max_connections = config.get("connections", 10config = {"timeout": 30, "retry": True}
timeout_value = config.get("timeout", 60)
max_connections = config.get("connections", 10)This code reads values from a dictionary called config. It uses the .get() method to retrieve values safely. timeout_value will be 30 (because it exists in the dictionary), while max_connections will be the default fallback 10 (because "connections" is not in the dictionary).
Key Takeaway: Using .get(key, default) prevents the code from crashing if a key doesn't exist.
def calculate_discount(price: float, discount_rate: float = 0.1) -> float:
return price - (price * discount_rate)This defines a function named calculate_discount that takes a price and an optional discount_rate (which defaults to 10% or 0.1). It returns the final price after the discount. The : float and -> float are type hints indicating what kind of data goes in and comes out.
Key Takeaway: Functions encapsulate reusable logic, and default parameters allow you to call the function with fewer arguments.
try:
result = 10 / 0
except ZeroDivisionError:
result = 0
print("Cannot divide by zero. Defaulting to 0.")This code attempts to divide 10 by 0, which normally crashes a program. The try block catches this specific error (ZeroDivisionError), allowing the except block to handle it gracefully by setting result to 0 and printing a warning.
Key Takeaway: try-except blocks protect your program from unexpected crashes by catching and managing errors.
with open("data.txt", "r") as file:
content = file.read()
print(content)This code opens a file named data.txt in read mode ("r"). The with statement acts as a context manager, meaning it automatically handles opening the file and, crucially, making sure it is properly closed when the block of code finishes—even if an error occurs while reading.
Key Takeaway: Always use the with statement when dealing with external resources like files or network connections to ensure they are safely cleaned up.
tasks = ["Deploy server", "Update database", "Restart services"]
for index, task in enumerate(tasks, start=1):
print(f"Task {index}: {task}")This code loops over the tasks list, but instead of just giving you the item, enumerate() gives you both the index (count) and the item itself. By passing start=1, the numbering begins at 1 instead of the default 0.
Key Takeaway: Use enumerate() when you need both the value of an item and its position (index) within a loop.
class NetworkNode:
def __init__(self, ip_address):
self.ip_address = ip_address
self.status = "Offline"
def connect(self):
self.status = "Online"
node_1 = NetworkNode("10.0.0.5")
node_1.connect()This defines a blueprint (a class) for creating NetworkNode objects. The __init__ method sets the initial state (an IP address and an "Offline" status) when a new node is created. We create node_1, then call its .connect() method to change its status to "Online".
Key Takeaway: Classes bundle data (ip_address, status) and the actions that modify that data (connect()) together into a single object.
logs = ["Error: 404", "Warning: High CPU", "Info: Restart", "Error: 500"]
recent_logs = logs[-2:]
reversed_logs = logs[::-1]This code uses slicing to extract specific parts of a list. Slicing uses the format [start:stop:step]. logs[-2:] grabs the last two items in the list. logs[::-1] uses a step of -1 to step backward through the entire list, effectively reversing it.
Key Takeaway: List slicing is a fast and powerful way to extract subsets of data or reverse sequences without writing loops.