Python Cheat Sheet

Complete Reference - All 5 Units Consolidated

UNIT I: Introduction to Python
Python Basics

Python is a high-level, interpreted, dynamically-typed language created by Guido van Rossum (1991).

print("Hello, World!")

Variables

name = "John" # No type declaration
x, y, z = 10, 20, 30 # Multiple
x, y = y, x # Swap values
Data Types
CategoryTypes
Textstr
Numericint, float, complex
Sequencelist, tuple, range
Mappingdict
Setset, frozenset
Booleanbool (True/False)
NoneNoneType

Type Conversion

int("100"), str(25), float(10), list("abc")
Arithmetic Operators
Additionx + y
Subtractionx - y
Multiplicationx * y
Divisionx / y
Floor Divisionx // y
Modulusx % y
Exponentiationx ** y
Comparison Operators
Equalx == y
Not equalx != y
Greater thanx > y
Less thanx < y
Greater or equalx >= y
Less or equalx <= y
Logical & Identity

Logical

ANDx and y
ORx or y
NOTnot x

Identity & Membership

Same objectx is y
Not samex is not y
In sequencex in y
Not inx not in y
Assignment Operators
Assignx = 5
Add & assignx += 3
Subtract & assignx -= 3
Multiply & assignx *= 3
Divide & assignx /= 3
Floor div & assignx //= 3
Modulus & assignx %= 3
Power & assignx **= 3
Bitwise Operators
OperatorDescription
&AND
|OR
^XOR
~NOT
<<Left shift
>>Right shift
Operator Precedence

Highest to Lowest:

PrecedenceOperator
1 (Highest)() Parentheses
2** Exponent
3~, +x, -x (Unary)
4*, /, //, %
5+, - (Binary)
6<<, >> (Shift)
7& (Bitwise AND)
8^ (Bitwise XOR)
9| (Bitwise OR)
10==, !=, <, >, <=, >=
11not
12and
13 (Lowest)or
UNIT II: Program Flow Control
Conditional Statements
if condition:
  # code
elif another:
  # code
else:
  # code

Ternary Operator

result = "Yes" if condition else "No"
For Loops
for item in iterable:
  print(item)

# With index
for i, item in enumerate(lst):
  print(i, item)
Range Function
SyntaxOutput
range(5)0, 1, 2, 3, 4
range(2, 7)2, 3, 4, 5, 6
range(0, 10, 2)0, 2, 4, 6, 8
range(10, 0, -1)10, 9, ...1
While Loops
count = 5
while count > 0:
  print(count)
  count -= 1

⚠️ Always update condition inside loop to avoid infinite loops!

Loop Control
breakExit loop immediately
continueSkip to next iteration
passDo nothing (placeholder)
elseRuns if no break
for i in range(10):
  if i == 5: break
else:
  print("No break")
Python Blocks

Python uses indentation (4 spaces) to define code blocks. No curly braces!

if True:
    print("Indented")
    if True:
        print("Nested")
Iteration Patterns
PatternExample
Iterate listfor x in list
With indexfor i, x in enumerate()
Two listsfor a, b in zip(x, y)
Dict keysfor k in dict
Dict itemsfor k, v in dict.items()
Reversefor x in reversed(list)
Nested Loops
for i in range(3):
  for j in range(3):
    print(i, j)
Use CasePattern
2D matrixfor row for col
Combinationsfor a for b
Pattern printNested range
UNIT III: Complex Data Types & Functions
Strings
text = "Hello, World!"
text[0] # 'H' (first char)
text[-1] # '!' (last char)
text[0:5] # 'Hello' (slice)
text[::-1] # Reverse string

f-Strings

name = "Alice"
print(f"Hello, {name}!")
String Methods
upper(), lower()Change case
strip()Remove whitespace
split(sep)Split to list
join(list)Join list to str
find(sub)Find index (-1 if not)
replace(old, new)Replace text
startswith()Check prefix
isdigit(), isalpha()Validation
Lists
my_list = [1, 2, "a", "b"]
my_list[0] # First item
my_list[-1] # Last item
my_list[1:3] # Slice [2, 'a']
my_list[0] = 10 # Mutable!

List Comprehension

[x**2 for x in range(5)]
[x for x in lst if x > 0]
List Methods
append(x)Add to end
insert(i, x)Add at index
extend(list)Add multiple
remove(x)Remove first x
pop(i)Remove & return
sort()Sort in-place
reverse()Reverse in-place
index(x)Find index
count(x)Count occurrences
Tuples

Immutable sequences - faster than lists, can be dict keys.

coords = (10, 20, 30)
x, y, z = coords # Unpacking
single = (5,) # Single element tuple

Tuple vs List

TupleImmutable, faster
ListMutable, flexible
Dictionaries
person = {"name": "Alice", "age": 25}
person["name"] # "Alice"
person["city"] = "NYC" # Add key
person.get("job", "N/A") # Safe access
keys()All keys
values()All values
items()Key-value pairs
update(d)Merge dicts
Functions
def greet(name, msg="Hello"):
  """Docstring"""
  return f"{msg}, {name}!"

greet("Alice") # "Hello, Alice!"
Lambda & *args/**kwargs

Lambda (Anonymous)

square = lambda x: x ** 2
square(5) # 25

*args & **kwargs

def func(*args, **kwargs):
  print(args) # Tuple
  print(kwargs) # Dict
Built-in Functions
len(x)Length
type(x)Get type
range(n)Number sequence
max(), min()Max/Min value
sum()Sum of iterable
sorted()Sorted copy
enumerate()Index + value
zip(a, b)Pair items
input()User input
Slicing Syntax
SyntaxResult
seq[start:end]Items start to end-1
seq[:end]From beginning
seq[start:]To end
seq[::step]Every step items
seq[::-1]Reverse
seq[-3:]Last 3 items
Sets
s = {1, 2, 3} # Unique items
MethodDescription
add(x)Add element
remove(x)Remove (error if missing)
discard(x)Remove (no error)
union(s2)All from both
intersection(s2)Common elements
difference(s2)In s1 not s2
Comprehensions
TypeSyntax
List[x for x in iter]
Dict{k:v for k,v in iter}
Set{x for x in iter}
Generator(x for x in iter)
squares = {x: x**2 for x in range(5)}
UNIT IV: File Operations
File Modes
ModeDescription
'r'Read (default)
'w'Write (overwrite)
'a'Append
'x'Exclusive create
'r+'Read + Write
'b'Binary ('rb', 'wb')
Reading Files
with open("file.txt", "r") as f:
  content = f.read() # All
  line = f.readline() # One line
  lines = f.readlines() # List
read()Entire file
readline()Single line
readlines()List of lines
for line in fIterate (best)
Writing Files
with open("file.txt", "w") as f:
  f.write("Hello\n")
  f.writelines(["a\n", "b\n"])

Note: write() doesn't add newlines automatically!

File Pointer
f.tell() # Current position
f.seek(0) # Go to start
f.seek(10) # Go to position 10

Context Manager (with) automatically closes files!

UNIT V: Python Packages & GUI
NumPy
import numpy as np

arr = np.array([1, 2, 3])
np.zeros((3, 4)) # 3x4 zeros
np.ones((2, 3)) # 2x3 ones
np.arange(0, 10, 2) # [0,2,4,6,8]
arr.shapeDimensions
arr.reshape()Reshape array
np.sum(), mean()Aggregations
arr.TTranspose
Pandas
import pandas as pd

df = pd.DataFrame({
  'Name': ['A', 'B'],
  'Age': [25, 30]
})
df = pd.read_csv('file.csv')
df['col']Select column
df.iloc[0]Row by index
df[df['Age']>25]Filter rows
df.head(n)First n rows
df.describe()Statistics
Matplotlib
import matplotlib.pyplot as plt

plt.plot(x, y)
plt.title('Title')
plt.xlabel('X'); plt.ylabel('Y')
plt.legend(); plt.show()
plt.plot()Line plot
plt.bar()Bar chart
plt.scatter()Scatter plot
plt.hist()Histogram
plt.pie()Pie chart
Tkinter Widgets
tk.Tk()Main window
tk.Label()Display text
tk.Button()Clickable button
tk.Entry()Text input
tk.Text()Multi-line input
tk.Frame()Container
tk.Checkbutton()Checkbox
tk.Listbox()Scrollable list
Tkinter Layout
MethodUse
pack()Simple stacking
grid(row, col)Table layout
place(x, y)Exact position
import tkinter as tk
root = tk.Tk()
root.title("App")
tk.Label(root, text="Hi").pack()
root.mainloop()
Error Handling
try:
  result = 10 / x
except ZeroDivisionError:
  print("Cannot divide by 0")
except Exception as e:
  print(e)
finally:
  print("Cleanup")
Common Errors
SyntaxErrorInvalid syntax
NameErrorUndefined variable
TypeErrorWrong type operation
ValueErrorWrong value
IndexErrorIndex out of range
KeyErrorDict key not found
FileNotFoundErrorFile doesn't exist
Classes (OOP)
class Person:
  def __init__(self, name):
    self.name = name

  def greet(self):
    return f"Hi, {self.name}"

p = Person("Alice")
p.greet() # "Hi, Alice"