Python Helper Sheet

Section C

Python Reference Guide

Hover for quick preview · Click to pin examples · Click again or X to close

Data Typeshover/click for example
boolean = True / FalseStores True or False values
integer = 10Whole numbers without decimals
float = 10.01Numbers with decimal points
string = "123abc"Text enclosed in quotes
list = [value1, value2, ...]Ordered, mutable collection
Numeric Operatorshover/click for example
+Addition
-Subtraction
*Multiplication
/Division (returns float)
**Exponent (power)
%Modulus (remainder)
//Floor division
Comparison Operatorshover/click for example
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
Boolean Operatorshover/click for example
andTrue if BOTH operands are True
orTrue if AT LEAST ONE is True
notReverses the boolean value
Special Charactershover/click for example
#Comment
\nNew line
\tTab
\⟨char⟩Escape character
Built-in Functionshover/click for example
print(x, sep="y")Print with custom separator
input(s)Read input from user
len(x)Length of x
min(L)Smallest item
max(L)Largest item
sum(L)Sum of items
range(n1, n2, n)Generate sequence
abs(n)Absolute value
round(n1, n)Round to n decimals
type(x)Type of x
str(x)Convert to string
list(x)Convert to list
int(x)Convert to integer
float(x)Convert to float
bool(x)Convert to boolean
pow(n1, n2)n1 to the power of n2
chr(x)Character for Unicode x
ord(x)Unicode code for char x
sorted(L)Sorted copy of list
map(function, L)Apply function to items
Assignment Operatorshover/click for example
=Simple assignment
+=Add and assign
-=Subtract and assign
*=Multiply and assign
%=Remainder and assign
/=Divide and assign
//=Floor divide and assign
String Operationshover/click for example
string[i]Access character at index i
string[-1]Access last character
string[i:j]Slice from i to j (exclusive)
String Methodshover/click for example
string.upper()Convert to uppercase
string.lower()Convert to lowercase
string.count(x)Count occurrences of x
string.find(x)Find first index of x
string.replace(x, y)Replace x with y
string.islower()Check if all lowercase
string.isupper()Check if all uppercase
string.isalnum()Check if alphanumeric
string.isalpha()Check if alphabetic
string.isdigit()Check if all digits
string.index(s)Find index of s (error if not found)
string.strip(x)Remove leading/trailing chars
Conditional Statementshover/click for example
if <condition>: <code>Execute if True
elif <condition>: <code>Check another condition
else: <code>If all conditions False
if <value> in <list>: <code>Check membership
Loopshover/click for example
while <condition>: <code>Repeat while True
for <variable> in <list>: <code>Iterate over list
for <variable> in range(start, stop, step): <code>Iterate over numbers
Loop Controlhover/click for example
breakExit the loop immediately
continueSkip current iteration
passPlaceholder (does nothing)
List Operationshover/click for example
list = []Create an empty list
list[i]Access value at index i
list[i] = xSet value at index i
list[-i]Access from end
list[i:j]Slice from i to j
list[i:]Slice from i to end
del list[i]Delete item at index i
List Methodshover/click for example
list.append(x)Add x to the end
list.extend(L)Add all items from L
list.insert(i, x)Insert x at index i
list.remove(x)Remove first x
list.pop(i)Remove & return item at i
list.clear()Remove all items
list.index(x)Index of first x
list.count(x)Count occurrences
list.sort()Sort in-place
list.reverse()Reverse in-place
list.copy()Return a shallow copy
File I/Ohover/click for example
f = open(<path>, 'r')Open file for reading
f.read(<size>)Read entire file
f.readline(<size>)Read a single line
for line in f: <code>Iterate over lines
f.close()Close the file
f = open(<path>, 'w')Open for writing
f.write(<str>)Write string to file
Functionshover/click for example
def function(<params>): <code>Define a function
return <data> or NoneReturn a value
Moduleshover/click for example
import moduleImport an entire module
module.function()Call a module function
from module import *Import all functions
function()Call imported function directly

⚠ Common Mistakes

if x = 5:
if x == 5:
= assigns, == compares
if x == 5 and 10:
if x == 5 and x < 10:
Be explicit on both sides of and/or
list.sort() returns new list
list.sort() sorts in-place (returns None)
Use sorted(list) for a new list
"5" + 3
int("5") + 3 or "5" + str(3)
Can't mix types with +
range(5) gives 1..5
range(5) gives 0,1,2,3,4 (stops before 5!)
range(stop) starts at 0
list[-0] for first item
list[0] — -0 is the same as 0
Use -1 for last item
b = my_list; b[0]=99
b = my_list.copy()
b = list makes a reference, not a copy
for i in range(len(list)):
for item in list: (when you just need the item)
Python has "for each" built in
if x > 0 or x < 10:
if x > 0 and x < 10:
Use and, not or, for range checks

★ Handy Patterns

F-Strings (with rounding)
name = "Alice"
age = 21
print(f"{name} is {age}")
# Alice is 21
print(f"2+2 = {2+2}")
# 2+2 = 4

# Rounding inside f-strings
pi = 3.14159265
print(f"Pi is {pi:.2f}")      # Pi is 3.14
print(f"Pi is {pi:.4f}")      # Pi is 3.1416
avg = 85.6666
print(f"Average: {avg:.1f}")  # Average: 85.7

# Padding and alignment
print(f"{"Left":<15}")  # Left
print(f"{"Right":>15}")  #           Right
print(f"{42:05d}")       # 00042
String Concatenation, Separators vs F-Strings
name = "Alice"
age = 21

# Using + for concatenation
print("Name: " + name + ", Age: " + str(age))
# Name: Alice, Age: 21

# Using separators in print
print("Name:", name, "Age:", age)
# Name: Alice Age: 21

# Using f-strings (more readable)
print(f"Name: {name}, Age: {age}")
# Name: Alice, Age: 21

# F-strings also allow expressions
print(f"In 5 years, {name} will be {age + 5} years old.")
# In 5 years, Alice will be 26 years old.
.split()
# Split string into a list
sentence = "Hello World Python"
words = sentence.split()
print(words)
# ['Hello', 'World', 'Python']

# Split by a specific character
csv = "Alice,21,Bob,22"
data = csv.split(",")
print(data)
# ['Alice', '21', 'Bob', '22']

# Split into max N parts
date = "2024-01-15"
parts = date.split("-", 2)
print(parts)
# ['2024', '01', '15']

# Common: reading CSV-style data
for line in open("data.txt"):
    name, age = line.strip().split(",")
    print(f"{name} is {age}")
.join()
words = ["Hello", "World", "Python"]

# Join with space
print(" ".join(words))
# Hello World Python

# Join with comma
print(", ".join(words))
# Hello, World, Python

# Join with newline
print("\n".join(words))
# Hello
# World
# Python

# Common: build a CSV line
row = ["Alice", "21", "A"]
line = ",".join(row)
print(line)  # Alice,21,A
.startswith() / .endswith()
filename = "report.pdf"

print(filename.endswith(".pdf"))   # True
print(filename.endswith(".docx"))  # False
print(filename.startswith("rep"))  # True

# Filter files by extension
files = ["a.pdf", "b.txt", "c.pdf"]
pdfs = [f for f in files if f.endswith(".pdf")]
print(pdfs)  # ['a.pdf', 'c.pdf']

# Check URL protocol
url = "https://example.com"
print(url.startswith("https://"))  # True
.isdigit() for input validation
# Validate user input is a number
age = input("Enter age: ")
if age.isdigit():
    age = int(age)
    print(f"You are {age} years old")
else:
    print("Please enter a valid number!")

# Check if all characters are digits
print("12345".isdigit())   # True
print("3.14".isdigit())    # False (has .)
print("abc".isdigit())     # False
Enumerate
fruits = ["apple", "banana", "cherry"]

# Get index and value
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# Start from a custom index
for i, fruit in enumerate(fruits, 1):
    print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry
File Handling
# Read a file
file = open("data.txt", "r")
content = file.read()
file.close()
print(content)

# Write to a file
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.close()

# Append to a file
file = open("output.txt", "a")
file.write("This is an additional line.\n")
file.close()