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 valuesinteger = 10Whole numbers without decimalsfloat = 10.01Numbers with decimal pointsstring = "123abc"Text enclosed in quoteslist = [value1, value2, ...]Ordered, mutable collectionNumeric Operatorshover/click for example
+Addition-Subtraction*Multiplication/Division (returns float)**Exponent (power)%Modulus (remainder)//Floor divisionComparison Operatorshover/click for example
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal toBoolean Operatorshover/click for example
andTrue if BOTH operands are TrueorTrue if AT LEAST ONE is TruenotReverses the boolean valueSpecial Charactershover/click for example
#Comment\nNew line\tTab\⟨char⟩Escape characterBuilt-in Functionshover/click for example
print(x, sep="y")Print with custom separatorinput(s)Read input from userlen(x)Length of xmin(L)Smallest itemmax(L)Largest itemsum(L)Sum of itemsrange(n1, n2, n)Generate sequenceabs(n)Absolute valueround(n1, n)Round to n decimalstype(x)Type of xstr(x)Convert to stringlist(x)Convert to listint(x)Convert to integerfloat(x)Convert to floatbool(x)Convert to booleanpow(n1, n2)n1 to the power of n2chr(x)Character for Unicode xord(x)Unicode code for char xsorted(L)Sorted copy of listmap(function, L)Apply function to itemsAssignment Operatorshover/click for example
=Simple assignment+=Add and assign-=Subtract and assign*=Multiply and assign%=Remainder and assign/=Divide and assign//=Floor divide and assignString Operationshover/click for example
string[i]Access character at index istring[-1]Access last characterstring[i:j]Slice from i to j (exclusive)String Methodshover/click for example
string.upper()Convert to uppercasestring.lower()Convert to lowercasestring.count(x)Count occurrences of xstring.find(x)Find first index of xstring.replace(x, y)Replace x with ystring.islower()Check if all lowercasestring.isupper()Check if all uppercasestring.isalnum()Check if alphanumericstring.isalpha()Check if alphabeticstring.isdigit()Check if all digitsstring.index(s)Find index of s (error if not found)string.strip(x)Remove leading/trailing charsConditional Statementshover/click for example
if <condition>:
<code>Execute if Trueelif <condition>:
<code>Check another conditionelse:
<code>If all conditions Falseif <value> in <list>:
<code>Check membershipLoopshover/click for example
while <condition>:
<code>Repeat while Truefor <variable> in <list>:
<code>Iterate over listfor <variable> in range(start, stop, step):
<code>Iterate over numbersLoop Controlhover/click for example
breakExit the loop immediatelycontinueSkip current iterationpassPlaceholder (does nothing)List Operationshover/click for example
list = []Create an empty listlist[i]Access value at index ilist[i] = xSet value at index ilist[-i]Access from endlist[i:j]Slice from i to jlist[i:]Slice from i to enddel list[i]Delete item at index iList Methodshover/click for example
list.append(x)Add x to the endlist.extend(L)Add all items from Llist.insert(i, x)Insert x at index ilist.remove(x)Remove first xlist.pop(i)Remove & return item at ilist.clear()Remove all itemslist.index(x)Index of first xlist.count(x)Count occurrenceslist.sort()Sort in-placelist.reverse()Reverse in-placelist.copy()Return a shallow copyFile I/Ohover/click for example
f = open(<path>, 'r')Open file for readingf.read(<size>)Read entire filef.readline(<size>)Read a single linefor line in f:
<code>Iterate over linesf.close()Close the filef = open(<path>, 'w')Open for writingf.write(<str>)Write string to fileFunctionshover/click for example
def function(<params>):
<code>Define a function return <data> or NoneReturn a valueModuleshover/click for example
import moduleImport an entire modulemodule.function()Call a module functionfrom module import *Import all functionsfunction()Call imported function directly⚠ Common Mistakes
if x = 5:
if x == 5:
= assigns, == comparesif x == 5 and 10:
if x == 5 and x < 10:
Be explicit on both sides of and/orlist.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 0list[-0] for first item
list[0] — -0 is the same as 0
Use -1 for last itemb = my_list; b[0]=99
b = my_list.copy()
b = list makes a reference, not a copyfor i in range(len(list)):
for item in list: (when you just need the item)
Python has "for each" built inif 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}") # 00042String 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()) # FalseEnumerate
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. cherryFile 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()