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
 

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
 

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)