Python Cheat Sheet - The Basics Edx
Python Cheat Sheet - The Basics Edx
Python Cheat Sheet - The Basics Edx
len(my_collection) Slicing
String Operations
Accessin g a subset of data from a strin g, list , or tu p le usin g element numbers from start to sto p -1
# Clone a lis t
a == b
# replaces any instance of the first string with the second in my_string
clone = my_collection [:]
my_string.replace('H', 'C') Less T han
a > b
my_integer = 12321
# C alculate the sum of a list of ints or floats
number_collection = [1,2,3,4.5]
G reater T han or E q ual
sum(number_collection)
Float a >= b
A decimal number
# Chec k if an item is in a list, returns B oolea n
Less T han or E q ual
my_decimal = 3.14 item in my_collectio n
# A dd an item to the se t
my_dictionary [ 'banana' ]
a.add( 4 )
Con d itional Operators
# R emo v e an item from a se t
Conditional Operators evaluate the operands and produce a true of false result
# Get all keys in a dictionary as a list
a.remo v e(" B ye")
my_dictionary. k eys() And - returns true if both statement a and b are true , otherwise false
# R eturns set a minus b
a.difference(b)
a and b
# Get all values in a dictionary as a list
tup = (1, 3.12, False, "Hi") # R eturns T rue if a is a su b set of b, false otherwise
not a
a.issu b set( b )
a.issuperset( b ) Page 1
soup = B eautiful S oup(html, ' html 5 lib ' ) # R eturns the file name
for x in iterable:
file . name
# Executes loop for each object in an iterable like a string, tuple, # R eturns formatted htm l
# R eturns the mode the file was opened i n
soup . prettif y ()
list, or set file . mode
file . read()
while statement:
# Executes the loop while statement is true # F ind all instances of an HTML ta g
soup . find_all(tag)
# R eads a certain number of characters of a file
file . read(characters)
Conditional Statements
Re qu ests
# R ead a single line of a file
if statement_1:
file . readline()
# Execute of statement_1 is true
# I mport the re q uests librar y
elif statement_2:
import re q uests
# R ead all the lines of a file and stores it in a lis t
file . readlines()
else:
file . close()
Try/Except # Get the url of the response
response . ur l
except a:
response . re q uest . header s
file = open(file_name, "w")
# Code to execute if there is an error of type a
# Get the body of the requests
except b:
response . header s
# Code to execute if there is any exception that has not been handled
else:
response . tex t
# Adds content to the end of a file
SyntaxError - When there is an error with how the code is written class class_name:
# code to execute
return optional_output
return optional_output
ran g e ( stop )
# Calling a function
# Create an instance of a class
Page 2