Uploaded by Richa Nayak

Python Cheat Sheet - The Basics CC

advertisement
Python Cheat Sheet: The Basics
Python Data Types
List
In d ex ing
Changeable collection of ob j ects
my_collection =
String
Accessing data from a string , list , or tu p le using an element number
[1, 1, 3.12, False, "Hi"]
my_tup [ element_number ]
List Operations
# returns the length of a lis t
Slicing
len(my_collection)
String Operations
Accessing a subset of data from a string , list , or tu p le using element numbers from start to sto p -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
Concatenate two lists
["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]
#
sum(number_collection)
Float
3.14
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
a =
b =
a =
b =
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()
# 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")
Greater Than or Equal
# R emo v e an item from a se t
a.remo v e(" B ye")
Less T han or Eq ual
a
<= b
Not Equal
!= b
Conditional Op erators evaluate the o p erands and p roduce 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
Con d itional Operators
#
Tu ple
Unchangeable collection of objects
> b
+: Additio
-: Subtractio
*: Multiplicatio
/: divisio
//: Integer Division (Result rounded to the nearest integer)
Set Operations
# R eturns set a minus
a.difference(b)
a
Python Operators
{100, 3.12, False, "Bye"}
{100, 3.12, "Welcome"}
Changeable collection of key - value p airs
my_dictionary =
< b
Greater Than
a
Set
Unordered collection of unique objects
True
False
a
a
A decimal number
my_decimal =
Com p arison Op erators com p are o p erands and return a result of true or false
Equal
my_collection_2 =
A whole number
my_collection [ start : stop ]
Co m parison Operators
#
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 on Cognitive Class
b
Or - returns true if either statement a or b are true, otherwise false
a or b
b
# R eturns T rue if a is a su b set of
a.issu b set( b )
Not - returns the opposite of the statement
b, false otherwise
# R eturns T rue if a is a superset of
a.issuperset( b )
b, false otherwise
not a
Page 1
© Copyright IB M Corporation 2021. A ll rights reser ve d .
Python Cheat Sheet: The Basics
We b scraping
Loops
For Loops
# Im port B eautiful S ou p
fro m bs 4 i m port B eautiful S oup
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
Wor k ing w ith Files
Reading a File
Opens a file in read mode
file = open(file_name, " r ")
#
# P arse HTML stored as a strin g
soup = B eautiful S oup(html, ' html 5 lib ' )
# R eturns the file name
file . name
# R eturns formatted htm l
soup . prettif y ()
# F ind the first instance of an HTML ta g
soup . find(tag)
While Loops
Learn Python for Data Science on Cognitive Class
# R eturns the mode the file was opened i n
file . mode
# R eads the contents of a file
file . read()
# 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)
Re qu ests
# R ead a single line of a file
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
try:
# Code
except a:
# Code
except b:
# Code
except:
# Code
else:
# Code
file . readline()
# I mport the re q uests librar y
import re q uests
# R ead all the lines of a file and stores it in a lis t
file . readlines()
# S end a get re q uests to the url with optional parameter s
response = re q uests . get(url, parameters)
Get the url of the response
response . ur l
# G et the status code of the response
#
file . close()
#
Writing to a File
response . status_code
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 headers of the request
response . re q uest . header s
#
#
Opens a file in write mode
"w")
file = open(file_name,
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
# S end a post re q uests to the url with optional parameter s
IndexError - When an index is out of rang
Closes a file
#
Writes content to a file
file . write(content)
#
Adds content to the end of a file
file . append(content)
Objects and Classes
re q uests . post(url, parameters)
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 se q uence from 0 to sto p -1
#
return optional_output
Code to execute
return optional_output
ran g e ( stop )
Produce an interable se q uence from start to sto p -1 incrementing by ste p
ran g e ( 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 m etho d
ob j ect .m ethod_na m e ( para m eter_ 3 )
Page 2
© Copyright IBM Corporation 2021. All rights reserved.
Download