Python Power Guide
Welcome to Your Python Cheat Sheet!
This is your interactive, "hand-holding" resource designed to help you review, practice, and master Python for your course.
We've translated the standard Python roadmap into an interactive experience. This widget is fully responsive and designed to work on both desktop and mobile. You'll find:
- Interactive Tables: Click buttons to see methods for lists, dictionaries, and strings.
- Dynamic Charts: Visualize how data aggregation works in real-time.
- Working Practice Terminals: Test your knowledge in each section with hands-on questions and get instant, intelligent feedback.
- Tricky Stuff: A special section dedicated to common mistakes and advanced techniques, explained with fun examples.
Use the menu to navigate between topics. Let's get started!
1. Python Fundamentals
This is the bedrock. Everything in Python is built on variables, data types, and operators. This section provides a quick, interactive refresher.
Variables & Core Data Types
A variable is a container. Python is dynamically typed, so you just assign a value with =.
- String (
str): Text."Hello"or'Hello' - Integer (
int): Whole numbers.10,-5 - Float (
float): Decimal numbers.3.14 - Boolean (
bool): Truth values.True,False(case-sensitive!) - NoneType (
None): Represents "nothing" or "empty".None
Operators
Arithmetic: +, -, *, / (true division), // (floor division), % (modulo), ** (exponent)
Comparison: == (equal value), != (not equal), >, <, >=, <=
Logical: and, or, not (use with booleans)
Membership: in, not in (check if item is in a sequence)
Identity: is, is not (check if two variables are the *same object* in memory)
f-Strings (Formatted Strings)
Introduced in Python 3.6, f-Strings are the easiest and most powerful way to embed variables directly into strings.
name = "Espy"
score = 95.5
# Just put an 'f' before the quotes
message = f"Hello, {name}! Your score is {score}."
print(message)
# Output: Hello, Espy! Your score is 95.5.
# You can even put expressions inside!
print(f"In 10 years, you will be... {10 + 25}?")
Practice Time
Q1: Create a variable named user_score and assign it the integer value of 100.
> Terminal ready. Awaiting code...
2. Data Structures
Data structures organize and store data. Click the buttons to see a cheat sheet of common methods for each type.
| Method/Operation | Example | Description |
|---|
Practice Time
Q1: Create a list named my_list containing the strings "apple", "banana", and "cherry".
> Terminal ready. Awaiting code...
3. Control Flow
Control flow dictates the order your code executes. Use if/elif/else for decisions and for/while loops for repetition.
Decision Making
temp = 25
if temp > 30:
print("It's hot!")
elif temp > 20:
print("It's warm.")
else:
print("It's cold.")
for Loop (Iteration)
# Loop over a list
fruits = ["apple", "banana"]
for fruit in fruits:
print(fruit)
# Loop a number of times
for i in range(3):
print(i) # Prints 0, 1, 2
while Loop (Condition)
count = 0
while count < 3:
print(count)
count += 1 # Don't forget!
Loop Modifiers
# break: Exits the loop entirely
for i in range(10):
if i == 3:
break
print(i) # Prints 0, 1, 2
# continue: Skips to the next
# iteration
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4
Practice Time
Q1: Write an if statement that prints "Access Granted" if a variable password is equal to the string "python123".
> Terminal ready. Awaiting code...
4. Functions & Scope
Functions (def) are reusable blocks of code. They help you organize your code and make it "DRY" (Don't Repeat Yourself).
Defining a Function
# A simple function with parameters
def greet(name):
return f"Hello, {name}!"
# Calling the function
message = greet("Espy")
print(message)
Advanced Arguments
# *args (variable-length arguments)
def add_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add_all(1, 2, 3)) # Output: 6
# **kwargs (keyword arguments)
def print_user(**user_data):
for key, value in user_data.items():
print(f"{key}: {value}")
print_user(id=1, name="Espy")
LEGB Scope Explorer
print(), len())
Python searches for variables from L → E → G → B.
Practice Time
Q1: Define a function named add_two that takes one number as an argument and returns that number plus 2.
> Terminal ready. Awaiting code...
5. Data Aggregation
Aggregation is the process of summarizing data. Before you learn libraries like Pandas, it's crucial to understand how to do this manually using loops and dictionaries.
Imagine you have a list of rap songs, and you want to count streams by album. Click the buttons to see the data aggregated in different ways.
Practice Time
Q1: You have a list: numbers = [1, 2, 3, 4, 5]. Write code to calculate the sum of this list and store it in a variable called total_sum. (Just write the calculation, assuming numbers exists).
> Terminal ready. Awaiting code...
6. Tricky Stuff & Power Moves
This is where you go from a user to a *power user*. This section covers common mistakes and advanced techniques, explained with fun examples.
Common Mistakes
Mistake 1: Mutable Default Arguments
A function's default arguments are created ONCE. If the default is a list, it will be shared across all calls.
# The WRONG way
def add_to_list(item, my_list=[]):
my_list.append(item)
return my_list
print(add_to_list('a')) # Output: ['a']
print(add_to_list('b')) # Output: ['a', 'b'] (Surprise!)
# The RIGHT way
def add_to_list_safe(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
Mistake 2: == vs is
== checks for **value**. is checks for **identity** (same object in memory). Always use is None.
list1 = [1, 2, 3] list2 = [1, 2, 3] print(list1 == list2) # Output: True (values are equal) print(list1 is list2) # Output: False (different objects)
Power Move: Comprehensions
Comprehensions are a fast, "Pythonic" way to create new lists, dicts, or sets from existing ones.
Example: The Candy Store
# A bag of mixed candies
candy_bag = ["snickers", "skittles", "milky way", "starburst"]
# The "long way" to get just the chocolate
chocolates = []
for candy in candy_bag:
if candy in ["snickers", "milky way"]:
chocolates.append(candy)
# The "List Comprehension" way
chocolates_fast = [c for c in candy_bag if c in ["snickers", "milky way"]]
# Create a dictionary of candy lengths
candy_lengths = {candy: len(candy) for candy in candy_bag}
# Output: {'snickers': 8, 'skittles': 8, ...}
Power Move: List Slicing
Slicing is a powerful way to get sub-sections of lists (and strings) using [start:stop:step] syntax.
Example: The Mixtape
# 0 1 2 3 4 songs = ["Track A", "Track B", "Track C", "Skit", "Track D"] # Get the first 3 songs # (start at 0, stop *before* 3) side_a = songs[0:3] # Output: ['Track A', 'Track B', 'Track C'] # Get the last 2 songs # (start at index 3, go to end) side_b = songs[3:] # Output: ['Skit', 'Track D'] # Get a copy of the whole list copy = songs[:] # Get every other song (step by 2) every_other = songs[::2] # Output: ['Track A', 'Track C', 'Track D'] # Reverse the list! reversed = songs[::-1] # Output: ['Track D', 'Skit', 'Track C', 'Track B', 'Track A']
Advanced: Intro to Pandas
Pandas is the *king* of data analysis in Python. It uses a structure called a DataFrame (like an Excel sheet). You'd need to pip install pandas to run this.
Example: Rapper Streams
import pandas as pd
# Data on rappers' album streams (in millions)
data = {
'artist': ['Kendrick', 'J. Cole', 'Kendrick', 'Drake', 'J. Cole'],
'album': ['TPAB', '2014 FHD', 'DAMN.', 'Scorpion', 'The Off-Season'],
'streams': [5000, 4500, 6000, 8000, 3000]
}
df = pd.DataFrame(data)
# This one line does what our chart in section 5 did!
artist_totals = df.groupby('artist')['streams'].sum()
print(artist_totals)
# Output:
# artist
# Drake 8000
# J. Cole 7500
# Kendrick 11000
Advanced: Decorators
A decorator is a function that *wraps* another function, adding new behavior without changing the original function's code. Think of it as a "hype man" for your function.
Example: The Hype Man
# The decorator (our hype man)
def hype_man(func_to_wrap):
def wrapper():
print("Y'all make some noise!") # Added behavior
func_to_wrap() # The original function runs
print("That was fire!") # Added behavior
return wrapper
# Using the decorator on our 'main_act'
@hype_man
def main_act():
print("...performing my hit song...")
# When you call main_act...
main_act()
# Output:
# Y'all make some noise!
# ...performing my hit song...
# That was fire!