lOMoARcPSD|4755966
Python cheat sheet - Lecture notes 1-19
Introduction to Algorithm and Python (Monash University)
StuDocu is not sponsored or endorsed by any college or university
Downloaded by Alan Kafaei (kafaeialireza@[Link])
lOMoARcPSD|4755966
Data Types Python cheat sheet
Type Conversion
Type Description Example
int 32 bit integer 2, -3 Method Description Example Output
float Floating point numbers 3.6, -5.98, 3.45e100 int(“34”)→34 Converts to integer 34 print(“34”)) 34
bool Boolean True, False int(“34.66”)→34 Truncates the fractional part print(“34.66”) 34
str Character sequence “Python”, “one\ntwo” int(“3f”,16)→63 Second parameter is the base print(int('3f',16)) 63
list Variable sequence [1,’two’,3.5] and it returns the number in
base 10
Lists float(“-11.28e8”)→-1128000000.0 Converts to float print(float('-11.28e8')) -1128000000.0
round(56.67,1)→56.7 Rounds to 1 decimal print(round(56.67,1)) 56.7
Lists are containers for holding values
Ex : if List is [‘apple’, ‘lemon’, ‘orange’, ‘grape’] chr(97)→a Returns the char of the code print(chr(97)) a
Positive Index 0 1 2 3 ‘97’
Negative Index -4 -3 -2 -1
ord(“a”)→97 Returns the code of char “a” print(ord(“a”)) 97
List[:-1] results in [‘apple’, ‘lemon’, ‘orange’]
List[1: ] results in [‘lemon’, ‘orange’, ‘grape’]
List[ : ] results in [‘apple’, ‘lemon’, ‘orange’, ‘grape’]
len(List) = 4
Variable assignment (=)
List Operations Situation Example Output
Method Return Value Example output Assign a single value to a variable x=2 2
[Link](obj) Appends obj to the end of list L=[] [] print(x) Python
Print(L) [1] Name= “Python”
[Link](1) [1,’apple’] print(Name)
print(L) [1,’apple’,2.3] Assign a formula or mathematical x=2+3 5
[Link]("apple") operation to a variable print(x)
print(L) Assign to multiple variables same value x=y=z=0 000
[Link](2.3)
print(x,y,z)
print(L)
Assign different values to multiple variables x,y,z=1,2,3 123
[Link]([index]) Returns item at specified index or L=[1,4,3,7] 7
item at the end of list x=[Link]() 4 or doing multiple assignments print(x,y,z)
print(x) [1,3] Swapping values a=2 32
y=[Link](1) b=3
print(y) a,b=b,a
print(L) print(a,b)
[Link](obj) Removes the first occurrence of L=[1,4,3,1,5] [4,3,1,5] Increment the value of a variable by 1 x=1 2
obj in L [Link](1) x+=1
print(L)
print(x)
[Link]() Reverses L in place L=[1,2,3,4,5] [5,4,3,2,1]
[Link]()
Decrement the value of a variable by 1 x=1 0
print(L) x-=1
[Link]() Sorts L in place L=[3,2,1,5,6] [1,2,3,5,6] print(x)
[Link]()
print(L)
Downloaded by Alan Kafaei (kafaeialireza@[Link])
lOMoARcPSD|4755966
String Operations
Conditional Statement (if)
Method Return Value Example output
[Link]() S with first char uppercase S=”python” Python Statement block gets executed only if a condition is true
S= [Link]()
print(S) Syntax: Example Output
[Link](sub) Non-overlapping S=’abababc’ 3 if logical condition1: if age<=18: “If the input age is 18”
occurrences of substring in count= [Link](‘ab’) statement block1 State= “cannot drive car” Output: cannot drive car
S print(count) print(State) “If the input age is 20”
[Link](sub) Index of first substring in S S=’abababc’ 0 Output: Does not prints anything
Pos=[Link](‘ab’) if logical condition2: if grade>=80: “If the input grade is 85”
print(Pos) statement block2 print(“HD”) Output: HD
[Link]() True if all the chars are S=’python123’ False elif logical condition3: elif grade>=60 and grade<80: “If the input grade is 60”
digits, false otherwise Flag=[Link]() statement block3 print(“D”) Output: D
print(Flag) else: else: “If the input grade is 45”
[Link]() True if S is all lowercase, S=’python’ True statement block4 print(“F”) Output: F
false otherwise Flag=[Link]()
print(Flag)
[Link]() True if S is all uppercase, S=’python’ False List of lists
false otherwise Flag=[Link]()
print(Flag) List of lists are often used to represent matrices or tables
[Link]() Converts S to all lowercase S=’PYTHON’ python
S=[Link]()
print(S) The above matrix is represented as a list of lists in the form [[1,2,3],[4,5,6],[7,8,9]]. The two
[Link]() Converts S to all uppercase S=’python’ PYTHON examples below show the method to create the list of lists as above. The list values are integers.
S=[Link]()
print(S) rows= int(input("Enter the number of rows=int(input("Enter the number of rows"))
[Link](seq) All items in seq S='-' p-y-t-h-o-n rows")) table=rows*[]
concatenated into a str, S= [Link]('python') table=rows*[0] for row in range(rows):
delimited by S print(S) for row in range(len(table)): line=input("enter items").split()
[Link]() Leading or trailing white S=' python is fun ' Python is fun cols=int(input("enter cols in row")) for i in range(len(line)):
space removed in S S=[Link]() table[row]=cols*[0] line[i]=int(line[i])
print(S) for col in range(cols): [Link](line)
[Link]([sep]) List of tokens in S, S=’python:is:fun’ [‘python’,’is’,’fun’] item=input("enter item") print(table)
delimited by sep: if sep not S=[Link](‘:’) table[row][col]=int(item)
given print(S) print(table)
Delimiter is any white #printing each line of the table, where #printing each sub-list of the table by #knowing
space. The arguments each line is #a sub-list #index of sub-list in the table
inside [] are optional.
for line in table: for counter in range (len(table)):
print (line) print (table[counter])
Downloaded by Alan Kafaei (kafaeialireza@[Link])
lOMoARcPSD|4755966
File Operations
Conditional Loop Statement Method Description Example output
open() It is used to open #example 1
Statement block gets executed as long as the condition is true the files. File opening modes can be filename = "[Link]" Opens the file named
specified. “r” for read, “w” for write file = open(filename, "r") “[Link]” and displays line
Syntax: Example and “a” for append. If nothing is for line in file: by line by looping through
specified in the second parameter, it print line the file object
while loop sum=0
is assumed as read mode. #example 2
counter=1
filename = "[Link]" Opens the file named
while logical condition: while(counter <=100):
file = open(filename, "r") “[Link]” and displays all
Statement sum = sum + counter
print([Link]()) lines at once
counter = counter +1
#example 3
print(“The sum of 100 numbers is”, sum)
filename = "[Link]"
for loop #example 1
file = open(filename, "r")
sum=0 print([Link]()) Prints the first line
for counter in range(101): # counter starts from 0 to 100 print([Link]()) Prints the second line
sum = sum + counter #example 4
print(“the sum is “, sum)
filename = "[Link]"
#example 2 file = open(filename, "r")
list=[1,2,3,4,5] print([Link]()) Reads all the lines in a list
sum=0 #example 5
for var in sequence: for counter in range(len(list)): filename = “[Link]”
Statement sum=sum+list[counter] file = open(filename, "r") Reads one character at a
print(“The sum of numbers in the list is”, sum) ch=[Link](1) time and prints them
while ch:
#example 3 ch=[Link](1)
list=[1,2,3,4,5] print (ch)
sum=0
for item in (list):
sum=sum+item write() It is used to write a sequence of file =open("[Link]","w") Writes the string “Hello
print(“The sum of numbers in the list is”, sum) strings to a file. [Link]("Hello World") World” in the file “[Link]”
close() It is used to close a file. file =open("[Link]","w") Writes the string “Hello
[Link]("Hello World") World” in the file “[Link]”
[Link]() and closes the file
split() Split is used to split the lines read file=open(“[Link]”,”r”) Opens a file named
from the file for line in file: “[Link]”. If the first line
line=[Link]() of the file is “Hello World”,
then [Link]() splits the
entire string as “Hello” and
“World”, with “Hello” being
stored in line[0] and “world
being stored in line[1]. The
subsequent lines in the file
are splitted the same way.
Downloaded by Alan Kafaei (kafaeialireza@[Link])