MIT 6.
0001 Comprehensive Python Cheat Sheet
1. Variables and Types
x = 10 # int
y = 3.14 # float
name = "Alice" # string
flag = True # boolean
x, y = y, x # swap values
2. Control Flow
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Less")
# Short-hand if:
result = "Yes" if x > 0 else "No"
3. Loops
# While loop
i = 0
while i < 5:
print(i)
i += 1
# For loop with range
for i in range(3): # 0,1,2
print(i)
# Looping over lists
for item in [1, 2, 3]:
print(item)
4. Functions & Scope
def square(x):
return x * x
def outer():
x = 10
def inner():
return x + 1
return inner()
print(outer()) # 11
MIT 6.0001 Comprehensive Python Cheat Sheet
5. Recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
6. Strings and String Methods
s = "hello"
s.upper(), s.lower(), s.find("e"), s.replace("e", "a")
s[1:4], len(s), s[::-1] # slicing and reverse
7. Lists
lst = [1, 2, 3]
lst.append(4)
lst[0] = 0
del lst[1]
squares = [x**2 for x in range(5)]
8. Tuples & Multiple Assignment
t = (1, 2)
a, b = t # unpacking
def f():
return (3, 4)
x, y = f()
9. Dictionaries
d = {"a": 1, "b": 2}
d["c"] = 3
for key in d:
print(key, d[key])
10. Higher-Order Functions & Lambdas
def apply_to_each(lst, f):
return [f(x) for x in lst]
print(apply_to_each([1,2,3], lambda x: x**2))
11. OOP: Classes and Objects
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
MIT 6.0001 Comprehensive Python Cheat Sheet
return self.name + " says Woof!"
d = Dog("Rex")
print(d.speak())
12. File I/O
# Write
with open("test.txt", "w") as f:
f.write("Hello\n")
# Read
with open("test.txt", "r") as f:
print(f.read())
13. Exception Handling
try:
x = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
14. Algorithms from the Course
# Bisection Method for square root
def bisect_sqrt(x, eps=0.01):
low, high = 0, max(1, x)
guess = (high + low)/2.0
while abs(guess**2 - x) > eps:
if guess**2 < x:
low = guess
else:
high = guess
guess = (high + low)/2.0
return guess
15. Newton-Raphson Method
def newton_raphson(f, df, x0, eps=1e-5):
x = x0
while abs(f(x)) > eps:
x = x - f(x)/df(x)
return x
# Example: sqrt(2)
f = lambda x: x**2 - 2
df = lambda x: 2*x
print(newton_raphson(f, df, 1.0))
MIT 6.0001 Comprehensive Python Cheat Sheet
16. Debugging & Testing
# Use print statements or IDE debuggers
# Use assert for testing:
assert square(3) == 9
print("All tests passed!")