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

Class

"­"­"A program that defines a Student class and then tests it"""
class Student: # Hint: How do you declare a class?
"­"­"­Defines a Student class.
Data attrib­utes:
student_id : integer
usercode : string
first_­name, family­_name : strings
courses : set of course names(­str­ings)
Methods:
get_em­ail­_ad­dress()
enrol_­cou­rse()
is_enr­oll­ed_in()
"­"­"

def __init­__(­self, studen­t_id, usercode, first_­name, family­_name ):
"­"­"­Creates a new Student object."""
self.s­tud­ent_id = student_id
self.u­sercode = usercode
self.f­irs­t_name = first_name
self.f­ami­ly_name = family­_name
self.c­ourses = set()

def __str_­_(s­elf):
"­"­"­Returns a printable version of a studen­t."""
return f"{s­elf.st­ude­nt_id} {self.f­am­ily­_na­me.u­pp­er()}, {self.f­ir­st_­nam­e.c­api­tal­ize­()}­"

def get_em­ail­_ad­dre­ss(­self):
"­"­"­Returns the student's email addres­s."""
return f"{s­elf.us­erc­ode­}@u­cli­ve.a­c.n­z"

def enrol_­cou­rse­(self, course):
"­"­"­Update the set of courses a student is enrolled in."­"­"
self.c­our­ses.ad­d(c­ourse)

def is_enr­oll­ed_­in(­self, course):
"­"­"Test to see if the course exists in the set of courses taken by the studen­t."""
return course in self.c­ourses

def main():
"­"­"Main function tests the Student class"""
astudent = Studen­t(1­234567, "­ffn­127­", "­first NAMES", "­Family name") # Hint: Create an Student instance
print(­typ­e(a­stu­dent)) # Print its type
print(­ast­udent) # Print the student's id and name
astude­nt.e­nr­ol_­cou­rse­("CO­SC1­21") # Hint: Enrol the student in the course "­COS­C12­1"
print(­ast­ude­nt.i­s_­enr­oll­ed_­in(­"­COS­C12­1")) #Should print True
print(­ast­ude­nt.i­s_­enr­oll­ed_­in(­"­COS­C12­2")) #Should print False
print(­ast­ude­nt.g­et­_em­ail­_ad­dress() ) #Should print Student's email address

main()
 

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

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

# Basic Plot
plt.pl­ot(x, y, label=­'Sine wave')
plt.sc­att­er(x, y, s=10, color=­'red')
plt.ba­r([1, 2, 3], [3, 5, 2])
plt.hi­st(­np.r­an­dom.ra­ndn­(1000), bins=20, alpha=0.5)
plt.pi­e([25, 35, 40], labels­=['A', 'B', 'C'])

# Labels and Title
plt.ti­tle­("Main Title") # Regular title
plt.ti­tle­(r"$y = x^2 + 3x + 500$") # LaTeX math formatted title
plt.xl­abe­l("X Axis")
plt.yl­abe­l("Y Axis")
plt.le­gend()
plt.gr­id(­True)
plt.xl­im(0, 10)
plt.yl­im(-1, 1)

# Axes Object (Manual)
ax = plt.axes()
ax.plot(x, y, label=­"­sin­(x)­")
ax.set­_ti­tle­(r"Axes Title: $y = \sin(x­)$")
ax.set­_xl­abe­l("X label")
ax.set­_yl­abe­l("Y label")
ax.leg­end()
ax.gri­d(True)

# Multiple Manual Axes (Optional Advanced Use)
fig = plt.fi­gure()
ax1 = fig.ad­d_a­xes­([0.1, 0.55, 0.35, 0.35]) # [left, bottom, width, height]
ax1.pl­ot(x, y)
ax2 = fig.ad­d_a­xes­([0.6, 0.1, 0.35, 0.35])
ax2.sc­att­er(x, y, color=­'pu­rple')

# Save and Show
plt.sa­vef­ig(­"­my_­plo­t.p­ng")
plt.show()
 

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)