Python Cheat Sheet: The Basics Python Data Types List In d ex ing Accessin g data from a strin g , list, or tuple usin g an element number Chan g eable collection of ob j ects my_collection = [1, 1, 3.12, False, "Hi"] String my_tup [ element_number ] List Operations # returns the length of a lis t Slicing len(my_collection) String Operations Accessin g a subset of data from a strin g , list, or tuple usin g element numbers from start to stop -1 # returns the string with all uppercase letters # my_string.upper() my_collection.extend( [ " M ore", " I tems" ] ) # returns the length of a string # Add multiple items to a list len(my_string) # returns the index of the first instance of the string inside the # # subject string, otherwise -1 del(my_collection [ 2 ] ) # replaces any instance of the first string with the second in my_string my_string.replace('H', 'C') Delete the object of a list at a specified index # Clone a lis t clone = my_collection [:] a == b Less T han ["a", "b", "c"] my_collection_3 = my_collection + my_collection_2 my_integer = 12321 # Calculate the sum of a list of ints or floats number_collection = [1,2,3,4.5] Boolean # Chec k if an item is in a list, returns Boolean in my_collection # Chec k if an item is not in a list, returns B oolea n item not in my_collection item Discrete value true or false Dictionary Chan g eable collection of key - value pairs my_dictionary = {'banana': 1, 12: 'laptop', (0,0):'center'} Dictionary Operations Access value using key my_dictionary [ 'banana' ] # Get all keys in a dictionary as a list my_dictionary. k eys() # Get all values in a dictionary as a list my_dictionary. v alues() a = b = Set Operations # Con v ert a list to a se t my_set = set( [ 1,1,2,3 ] ) # A dd an item to the se t a.add( 4 ) tup = (1, 3.12, False, "Hi") Less T han or Eq ual a <= b Not Equal != b Con d itional Operators # R emo v e an item from a se t a.remo v e(" B ye") Conditional O perators evaluate the operands and produce a true of false result And - returns true if both statement a and b are true, otherwise false b a and b # R eturns intersection of set a and a.intersection(b) # R eturns the union of set a and a.union(b) >= b +: Additio -: Subtractio *: Multiplicatio /: divisio //: Integer Division (Result rounded to the nearest integer) # Tu ple Unchangeable collection of objects > b Python Operators {100, 3.12, False, "Bye"} {100, 3.12, "Welcome"} # R eturns set a minus a.difference(b) a a Set Unordered collection of unique objects a = True b = False < b Greater Than a A decimal number my_decimal = 3.14 a Greater Than or Equal sum(number_collection) Float Comparison O perators compare operands and return a result of true or false Equal my_collection_2 = A whole number my_collection [ start : stop ] Co m parison Operators # Concatenate two lists Integer my_string [ start : stop ] my_tup [ start : stop ] Add a single item to a list my_collection.append(" S ingle") my_string.find('l') my_string [ element_number ] my_collection [ element_number ] Series of characters or data stored as text my_string = "Hello" Learn Python for Data Science, AI & Development on Coursera b b # R eturns T rue if a is a subset of b, false otherwis e a.issubset(b) # R eturns T rue if a is a superset of b, false otherwis e a.issuperset(b) Or - returns true if either statement a or b are true, otherwise false a or b Not - returns the opposite of the statement not a Page 1 © Copyright IB M Corporation 2021. A ll rights reser ve d . Python Cheat Sheet: The Basics Wor k ing w ith Files Webscraping Loops For Loops Reading a File # Import BeautifulSoup from bs4 import BeautifulSoup for x in range(x): # Executes loop x number of times for x in iterable: # Executes loop for each object in an iterable like a string, tuple, list, or set while statement: # Executes the loop while statement is true Conditional Statements Opens a file in read mode file = open(file_name, " r ") # R eturns the file name file . name # R eturns the mode the file was opened i n file . mode # # P arse HTML stored as a strin g soup = B eautiful S oup(html, ' html 5 lib ' ) # R eturns formatted htm l soup . prettif y () # F ind the first instance of an soup . find(tag) While Loops Learn Python for Data Science, AI & Development on Coursera # F ind all instances of an soup . find_all(tag) HTML tag Reads the contents of a file file . read() # HTML tag Re qu ests Reads a certain number of characters of a file file . read(characters) # Read a single line of a file file . readline() # if statement_1: # Execute of statement_1 is true elif statement_2: # Execute if statement_1 is false and statement_2 is true else: # Execute if all previous statements are false Try/Except # Import the re q uests librar y import re q uests # # to try to execute to execute if there is an error of type a to execute if there is an error of type b to execute if there is any exception that has not been handled to execute if there is no exception Get the url of the response response . ur l # try: # Code except a: # Code except b: # Code except: # Code else: # Code Send a get requests to the url with optional parameters = requests.get(url, parameters) response Get the status code of the response Closes a file file . close() # Writing to a File response . status_code # Get the headers of the request response . re q uest . header s # # Opens a file in write mode = open(file_name, "w") file Get the body of the requests response . re q uest . bod y Get the headers of the response response . header s # G et the content of the response in tex t response . tex t # G et the content of the response in j so n response .j son () # Error Types Send a post requests to the url with optional parameters re q uests . post(url, parameters) # IndexError - When an index is out of rang Read all the lines of a file and stores it in a list file . readlines() # # Writes content to a file file . write(content) # Adds content to the end of a file file . append(content) Objects and Classes Creating a class NameError - When a variable name is not foun # SyntaxError - When there is an error with how the code is written class class_name: ZeroDivisionError - When your code tries to divide by zero Range F u nctions def __init__(self . optional_parameter_1, optional_parameter_2): self . attribute_1 # = optional_parameter_1 self . attribute_2 = optional_parameter_ 2 Create a function def function_name(optional_parameter_1, optional_prameter_2): def method_name(self, optional_parameter_1): # code to execute Produce an iterable sequence from 0 to stop-1 # return optional_output Code to execute return optional_output range(stop) Produce an interable sequence from start to stop-1 incrementing by step range(start, stop, step) Calling a function output = function_name(parameter_1, parameter_2) # Create an instance of a class object = class_name(parameter_1, parameter_2) # # Callin g an ob j ect metho d ob j ect . method_name ( parameter_ 3) Page 2 © Copyright IBM Corporation 2021. All rights reserved.