Show Menu
Cheatography

python 121 Cheat Sheet (DRAFT) by

this is for my final exam for cosc 121 abiut python basic programming

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Files

file = open("d­ata.tx­t") # open file
contents = file.r­ead() # whole file as string
lines = file.r­ead­lines() # all lines as list
line = file.r­ead­line() # one line
for line in file: # loop lines
line = line.s­trip() # remove \n and spaces
parts = line.s­pli­t(",­") # split by comma
file.c­lose() # close file

annoying for loops

# --- Compact Python Cheat Sheet with Examples ---

# 1. In-place list update
def thresh­old­_fi­lte­r(r­ead­ings, thresh­old):
for i in range(­len­(re­adi­ngs)):
readin­gs[i] = 0 if readin­gs[i] < 0 else (threshold if readin­gs[i] <= threshold else readin­gs[i])

r = [-3, 0, 2, 8, 15]
thresh­old­_fi­lter(r, 5)
print(r) # [0, 5, 5, 8, 15]

# 2. Count words in order
def word_c­oun­ter(s):
counts = {}
for w in s.lowe­r().sp­lit():
counts[w] = counts.get(w, 0) + 1
return counts

print(­wor­d_c­oun­ter­("Hi there hi There")) # {'hi': 2, 'there': 2}

# 3. Sum list until threshold (while loop)
def sum_li­st_­unt­il(­nums, t):
i, total = 0, 0
while i < len(nums) and total < t:
total += nums[i]
i += 1
return i, total

print(­sum­_li­st_­unt­il(­[5,­6,6,4], 17)) # (3, 17)

# 4. Running total with labels
def units_­ava­ila­ble­(data):
total = 0
return [(tota­l:=­tot­al+­change, label) for change, label in data]

print(­uni­ts_­ava­ila­ble­([(­15,­"­Mon­"), (-5,"Tu­e"), (0,"­Wed­")]))
# [(15, 'Mon'), (10, 'Tue'), (10, 'Wed')]

# 5. Index courses by keys
def index_­cou­rse­(gr­ades):
d = {}
for i, entry in enumer­ate­(gr­ades):
d.setd­efa­ult­(en­try­['c­our­se_­id'], []).ap­pend(i)
return d

grades = [
{'stud­ent­_id­':1­,'c­our­se_­id'­:'c­osc­121­','­gra­de'­:'A'},
{'stud­ent­_id­':2­,'c­our­se_­id'­:'c­osc­122­','­gra­de'­:'B'},
{'stud­ent­_id­':3­,'c­our­se_­id'­:'c­osc­121­','­gra­de'­:'C'}
]
print(­ind­ex_­cou­rse­(gr­ades)) # {'cosc­121­':[­0,2], 'cosc1­22'­:[1]}

# 6. Dict compre­hension
words = ['hello', 'world']
word_l­engths = {w: len(w) for w in words}
print(­wor­d_l­engths) # {'hello': 5, 'world': 5}

# 7. List compre­hension with condition
thresh­olded = [x if x > 5 else 5 for x in [-2,4,­8,10]]
print(­thr­esh­olded) # [5, 5, 8, 10]

# 8. Using enumerate
for i, v in enumer­ate­(['­a',­'b'­,'c']):
print(i, v)
# 0 a
# 1 b
# 2 c

# 9. Sorted dict keys output
my_dict = {'b': 2, 'a': 1, 'c': 3}
for k in sorted­(my­_dict):
print(k, my_dic­t[k])
# a 1
# b 2
# c 3
 

exceptions

except ZeroDi­vis­ion­Error:
except ValueE­rror:
except IndexE­rror:
except TypeError:

list slicing

nums = [10, 20, 30, 40, 50, 60]
nums[1:4] [20, 30, 40]
nums[:3]. [10, 20, 30]
nums[-2:] last 2 items
nums[:-1] all but last
nums[::2] every 2nd item
nums[:­:-1]. reverse

If statment

if num % 2 == 0: #even
if num % 2 != 0: #odd
6 / 2 #3.0
7 // 2 #3
7 % 2 #1
3 ** 2 #9

matplotlib

import matplo­tli­b.p­yplot as plt
import numpy as np

# ======= BASIC LINE PLOT =======
x = np.lin­spa­ce(0, 10, 100)
y = np.sin(x)

plt.pl­ot(x, y, label=­'si­n(x)') # Line plot
plt.ti­tle­("Sine Curve") # Title
plt.xl­abe­l("x­-ax­is") # X label
plt.yl­abe­l("y­-ax­is") # Y label
plt.gr­id(­True) # Show grid
plt.le­gend() # Show legend
plt.xl­im(0, 10) # Limit x-axis
plt.yl­im(-1, 1) # Limit y-axis
plt.xt­ick­s([0, 5, 10]) # Custom x ticks
plt.yt­ick­s([-1, 0, 1]) # Custom y ticks
plt.sa­vef­ig(­"­sin­e_p­lot.pn­g") # Save to file
plt.show() # Show the plot

# ======= SCATTER PLOT =======
x = np.ran­dom.ra­nd(50)
y = np.ran­dom.ra­nd(50)
plt.sc­att­er(x, y)
plt.ti­tle­("Random Scatte­r")
plt.show()

# ======= BAR CHART =======
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.ba­r(c­ate­gories, values)
plt.ti­tle­("Bar Chart")
plt.show()

# ======= HISTOGRAM =======
data = np.ran­dom.ra­ndn­(1000)
plt.hi­st(­data, bins=30)
plt.ti­tle­("Hi­sto­gra­m")
plt.show()

# ======= CLEARING / CLOSING =======
plt.clf() # Clear current figure (if needed)
plt.cl­ose() # Close the plot window
 

For Loops

for i in range(5): print(i) # 0 1 2 3 4
for i in range(­2,6): print(i) # 2 3 4 5
for i in range(­1,1­0,3): print(i) # 1 4 7

lst=['­a',­'b'­,'c']
for i in range(­len­(lst)): print(­i,l­st[i]) # 0 a 1 b 2 c
for item in lst: print(­item) # a b c
for i,item in enumer­ate­(lst): print(­i,item) # 0 a 1 b 2 c

switching while loop to for loop

# For loops
for op1 in range(0, value1):
for op2 in range(­value1, value2, -1):
print(­f"{o­p1:3} x {op2:3} = {op1*o­p2:­3}")

# Equivalent while loops
op1 = 0
while op1 < value1:
op2 = value1
while op2 > value2:
print(­f"{o­p1:3} x {op2:3} = {op1*o­p2:­3}")
op2 -= 1
op1 += 1

annoying for loop on dict

# for key, value in dict.i­tems()
d = {'a':1­,'b':2}
for k,v in d.items(): print(k,v)
# Before: d = {'a':1­,'b':2}
# After:
# a 1
# b 2

# for word in string.sp­lit()
s = " hello world "
for w in s.stri­p().sp­lit(): print(w)
# Before: " hello world "
# After:
# hello
# world

# for i in range(­len­(list))
lst = ['x','y']
for i in range(­len­(lst)): print(­i,l­st[i])
# Before: ['x','y']
# After:
# 0 x
# 1 y

# for i in range(­start, stop, step)
for i in range(­1,6,2): print(i)
# Before: range(­1,6,2)
# After:
# 1
# 3
# 5

# for i, val in enumer­ate­(list)
lst = ['a','b']
for i,v in enumer­ate­(lst): print(i,v)
# Before: ['a','b']
# After:
# 0 a
# 1 b
 

Sets and Dictio­naries

# Sets from list and operations
lst=[1­,2,­2,3­,4,4]
s=set(lst) # {1,2,3,4}
s.add(5) # {1,2,3­,4,5}
s.remo­ve(2) # {1,3,4,5}
s.disc­ard(6) # {1,3,4,5} no error
print(3 in s) # True
s2={3,­4,5,6}
print(­s.u­nio­n(s2)) # {1,3,4­,5,6}
print(­s.i­nte­rse­cti­on(­s2))# {3,4,5}
print(­s.d­iff­ere­nce­(s2)) # {1}
print(­s.i­ssu­bse­t(s2)) # False
for x in s: print(x) # 1 3 4 5 (any order)

# Dictio­naries and methods
d={"­a":1­,"b":2}
print(­d.k­eys()) # dict_k­eys­(['­a',­'b'])
print(­d.v­alu­es()) # dict_v­alu­es(­[1,2])
print(­d.i­tems()) # dict_i­tem­s([­('a­',1­),(­'b'­,2)])
print(­d.g­et(­"­a")) # 1
print(­d.g­et(­"­z",0)) # 0 default if missing
d["c­"]=3
for k in d: print(k) # a b c
for v in d.valu­es(): print(v) # 1 2 3
for k,v in d.items(): print(k,v) # a 1 b 2 c 3

Lists

fruits = ["ap­ple­", "­ban­ana­", "­che­rry­"]
fruits[0] #apple
fruits[-1] #cherry
len(fr­uits) #3
fruits.ap­pen­d("k­iwi­")
fruits.in­sert(1, "­pea­r")
fruits.re­mov­e("b­ana­na")
fruits.pop() #removes last
fruits.sort()
sorted­(fr­uits)