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

Python Cheat Sheet - The Basics Coursera

Python Cheat Sheet: The Basics provides an overview of Python data types, operations, and comparison operators. It discusses the basics of strings, lists, tuples, indexing, slicing, and common list operations like appending, extending, deleting, and cloning elements. The document serves as a quick reference guide for Python fundamentals.

Uploaded by

satishrs.inspire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

Python Cheat Sheet - The Basics Coursera

Python Cheat Sheet: The Basics provides an overview of Python data types, operations, and comparison operators. It discusses the basics of strings, lists, tuples, indexing, slicing, and common list operations like appending, extending, deleting, and cloning elements. The document serves as a quick reference guide for Python fundamentals.

Uploaded by

satishrs.inspire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Cheat Sheet: The Basics Learn Python for Data Science, AI & Development on Coursera

Python Data Types


L ist In d x e ing

Chan g eable collection of ob ects j Accessin g data from a strin g , list, or tuple usin g an element number

String
my collection
_ = [1, 1, 3 12, False, . "H i ] "
my_string [ element_number ]

Series of characters or data stored as text my_collection [ element_number ]

L ist Operations
my_tup [ element_number ]
my_string = "Hello"

# 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

# A dd multiple items to a lis t


my_string [ start : stop ]

my_string.upper()
my_collection.extend( [ M " ore", " I tems" ] )
my_collection [ start : stop ]

my_tup [ start : stop ]


# returns the length of a string

# A dd a single item to a lis t

len(my_string)
my_collection.append(" S ingle")

Co m parison Operators

# returns the index of the first instance of the string inside the

# D elete the object of a list at a specified inde x


Comparison O perators compare operands and return a result of true or false
# subject string, otherwise -1

del(my_collection [ ] 2 )

my_string.find('l') Eq ual

# 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

# Concatenate two lists

a < b

Integer
my_collection_2 = [ "a", "b", "c" ]

A whole number
my_collection_3 = my_collection + my_collection_2 G reater T han

my_integer = 12321
a > b

# Calculate the sum of a list of ints or floats

number_collection = [ 1,2,3, 4 5]

. G reater T han or Eq 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 Eq ual

my decimal
_ = 3 14.
item in my_collectio n

# Chec k if an item is not in a list, returns B oolea n


a < = b

not in
N Eq
item my_collection
Boolean ot ual

Discrete value true or false

a ! = b

a = True
Set

b = False U nordered collection of uni q ue ob ects j

a = { 00
1 , 3.12, F alse, " B ye" }
Python Operators

Dictionary
b = { 00
1 , 3.12, " W elcome" }
Chan g eable collection of k -
ey value pairs
+: Additio

-:
{ : : 0 0 : } Set Operations Subtractio
my_dictionary = 'banana' 1, 12 'laptop', ( , ) 'center'

*: M ultiplicatio

# Con v ert a list to a se t


/:divisio
[ ]
//: g (R g )
my_set = set( 1,1,2,3 )
Dictionary Operations Inte er Division esult rounded to the nearest inte er

A t

A v k y

# dd an item to the se

4
d
# ccess alue using e
a.add( )

my_dictionary [ 'banana' ] Con itional Operators

# R emo v e an item from a se t


Conditional O perators evaluate the operands and produce a true of false result

# G et all k eys in a dictionary as a lis t


a.remo v e(" B ye")

my_dictionary. k eys()
-
R b

And returns true if both statement a and b are true, otherwise false
# eturns set a minus

a.difference(b)

# G et all v alues in a dictionary as a lis t


a and b

my_dictionary. v alues()
# R eturns intersection of set a and b
O - r returns true if either statement a or b are true, otherwise false
a.intersection(b)

a or b

Tu ple # R eturns the union of set a and b

U nchan g eable collection of ob ects j a.union(b) N - ot returns the opposite of the statement

tup = (1, 3.12, F alse, "Hi")


# R eturns T rue if a is a subset of b, false otherwis e
not a

a.issubset(b)

# R eturns T rue if a is a superset of b, false otherwis e

a.issuperset(b) Page 1

© Copyright IB M Corporation 2021. A ll rights reser v e d .


Python Cheat Sheet: The Basics Learn Python for Data Science, AI & Development on Coursera

Loops Webscraping Wor k ing w ith Files

For Loops # Import BeautifulSoup


Reading a File
from bs4 import BeautifulSoup
for x in range(x):
# Opens a file in read mode

# Executes loop x number of times # P arse HTML stored as a strin g


file = open(file_name, " r ")

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

# F ind the first instance of an HTML tag

While Loops soup . find(tag) # Reads the contents of a file

file . read()
while statement:

# Executes the loop while statement is true # F ind all instances of an HTML tag

soup . find_all(tag)
# Reads a certain number of characters of a file

file . read(characters)
Conditional Statements
Re qu ests
# Read a single line of a file

if statement_1:
file . readline()
# Execute of statement_1 is true
# Import the re q uests librar y

elif statement_2:
import re q uests
# Read all the lines of a file and stores it in a list

# Execute if statement_1 is false and statement_2 is true

file . readlines()
else:

# Send a get requests to the url with optional parameters

# Execute if all previous statements are false


response = requests.get(url, parameters)
# Closes a file

file . close()
Try/Except # Get the url of the response

response . ur l

# Get the status code of the response


Writing to a File
try:
response . status_code

# Code to try to execute


# Get the headers of the request
# Opens a file in write mode

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 . re q uest . bod y

# Code to execute if there is an error of type b


# Writes content to a file

# Get the headers of the response


file . write(content)
except:

response . header s

# Code to execute if there is any exception that has not been handled

# G et the content of the response in tex t

else:

response . tex t
# Adds content to the end of a file

# Code to execute if there is no exception


# G et the content of the response in j so n
file . append(content)
response .j son ()
Error Types
Objects and Classes
# Send a post requests to the url with optional parameters

re q uests . post(url, parameters)


IndexError - When an index is out of rang
NameError - When a variable name is not foun # Creating a class

SyntaxError - When there is an error with how the code is written class class_name:

ZeroDivisionError - When your code tries to divide by zero


F u nctions def __init__(self . optional_parameter_1, optional_parameter_2):

self . attribute_1 = optional_parameter_1

self . attribute_2 = optional_parameter_ 2

Range # 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 # Code to execute

return optional_output
return optional_output
range(stop)
# Calling a function
# Create an instance of a class

Produce an interable sequence from start to stop-1 incrementing by step


output = function_name(parameter_1, parameter_2)
object = class_name(parameter_1, parameter_2)
range(start, stop, step)

# Callin g an ob j ect metho d

ob j ect . method_name ( parameter_ 1)

Page 2
© Copyright IBM Corporation 2021. All rights reserved.

You might also like