0% found this document useful (0 votes)
85 views

Python Cheat Sheet - Lecture Notes 1-19 Python Cheat Sheet - Lecture Notes 1-19

This document provides a summary of key concepts in Python including: - Common data types like integers, floats, booleans, strings, and lists - Operations that can be performed on lists like append, pop, remove, reverse, and sort - Operations on strings like capitalize, count, and find - Type conversion methods like int(), float(), round(), chr(), and ord() - Variable assignment and arithmetic operators - Conditional statements using if The cheat sheet covers basic Python syntax for these common data types, operations, and control flow over 3 pages of lecture notes.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Python Cheat Sheet - Lecture Notes 1-19 Python Cheat Sheet - Lecture Notes 1-19

This document provides a summary of key concepts in Python including: - Common data types like integers, floats, booleans, strings, and lists - Operations that can be performed on lists like append, pop, remove, reverse, and sort - Operations on strings like capitalize, count, and find - Type conversion methods like int(), float(), round(), chr(), and ord() - Variable assignment and arithmetic operators - Conditional statements using if The cheat sheet covers basic Python syntax for these common data types, operations, and control flow over 3 pages of lecture notes.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

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 ([email protected])
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
L.append(obj) Appends obj to the end of list L=[] [] print(x) Python
Print(L) [1] Name= “Python”
L.append(1) [1,’apple’] print(Name)
print(L) [1,’apple’,2.3] Assign a formula or mathematical x=2+3 5
L.append("apple") operation to a variable print(x)
print(L) Assign to multiple variables same value x=y=z=0 000
L.append(2.3)
print(x,y,z)
print(L)
Assign different values to multiple variables x,y,z=1,2,3 123
L.pop([index]) Returns item at specified index or L=[1,4,3,7] 7
item at the end of list x=L.pop() 4 or doing multiple assignments print(x,y,z)
print(x) [1,3] Swapping values a=2 32
y=L.pop(1) b=3
print(y) a,b=b,a
print(L) print(a,b)
L.remove(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 L.remove(1) x+=1
print(L)
print(x)
L.reverse() Reverses L in place L=[1,2,3,4,5] [5,4,3,2,1]
L.reverse()
Decrement the value of a variable by 1 x=1 0
print(L) x-=1
L.sort() Sorts L in place L=[3,2,1,5,6] [1,2,3,5,6] print(x)
L.sort()
print(L)

Downloaded by Alan Kafaei ([email protected])


lOMoARcPSD|4755966

String Operations
Conditional Statement (if)
Method Return Value Example output
S.capitalize() S with first char uppercase S=”python” Python Statement block gets executed only if a condition is true
S= S.capitalize()
print(S) Syntax: Example Output
S.count(sub) Non-overlapping S=’abababc’ 3 if logical condition1: if age<=18: “If the input age is 18”
occurrences of substring in count= S.count(‘ab’) statement block1 State= “cannot drive car” Output: cannot drive car
S print(count) print(State) “If the input age is 20”
S.find(sub) Index of first substring in S S=’abababc’ 0 Output: Does not prints anything
Pos=S.find(‘ab’) if logical condition2: if grade>=80: “If the input grade is 85”
print(Pos) statement block2 print(“HD”) Output: HD
S.isdigit() 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=S.isdigit() statement block3 print(“D”) Output: D
print(Flag) else: else: “If the input grade is 45”
S.islower() True if S is all lowercase, S=’python’ True statement block4 print(“F”) Output: F
false otherwise Flag=S.islower()
print(Flag)
S.isupper() True if S is all uppercase, S=’python’ False List of lists
false otherwise Flag=S.isupper()
print(Flag) List of lists are often used to represent matrices or tables
S.lower() Converts S to all lowercase S=’PYTHON’ python
S=S.lower()
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
S.upper() 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=S.upper()
print(S) rows= int(input("Enter the number of rows=int(input("Enter the number of rows"))
S.join(seq) All items in seq S='-' p-y-t-h-o-n rows")) table=rows*[]
concatenated into a str, S= S.join('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()
S.strip() 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=S.strip() table[row]=cols*[0] line[i]=int(line[i])
print(S) for col in range(cols): table.append(line)
S.split([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=S.split(‘:’) 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 ([email protected])


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 = "hello.txt" Opens the file named
specified. “r” for read, “w” for write file = open(filename, "r") “hello.txt” 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 = "hello.txt" Opens the file named
while logical condition: while(counter <=100):
file = open(filename, "r") “hello.txt” and displays all
Statement sum = sum + counter
print(file.read()) lines at once
counter = counter +1
#example 3
print(“The sum of 100 numbers is”, sum)
filename = "hello.txt"
for loop #example 1
file = open(filename, "r")
sum=0 print(file.readline()) Prints the first line
for counter in range(101): # counter starts from 0 to 100 print(file.readline()) Prints the second line
sum = sum + counter #example 4
print(“the sum is “, sum)
filename = "hello.txt"
#example 2 file = open(filename, "r")
list=[1,2,3,4,5] print(file.readlines()) Reads all the lines in a list
sum=0 #example 5
for var in sequence: for counter in range(len(list)): filename = “hello.txt”
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=file.read(1) time and prints them
while ch:
#example 3 ch=file.read(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("hello.txt","w") Writes the string “Hello
print(“The sum of numbers in the list is”, sum) strings to a file. file.write("Hello World") World” in the file “hello.txt”

close() It is used to close a file. file =open("hello.txt","w") Writes the string “Hello
file.write("Hello World") World” in the file “hello.txt”
file.close() and closes the file
split() Split is used to split the lines read file=open(“hello.txt”,”r”) Opens a file named
from the file for line in file: “hello.txt”. If the first line
line=line.split() of the file is “Hello World”,
then line.split() 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 ([email protected])

You might also like