CheatSheet

Python Cheat Sheet : The Basics

Data Types

String

Series of characters or data stored as text my_string = “Hello”

String Operations

Integer

A whole number

my_integer = 12321

Float

A decimal number

my_decimal = 3.14

Boolean

Discrete value true or false

a = True
b = False

Dictionary

Changeable collection of key-value pairs

my_dictionary = {'banana': 1, 12: 'laptop', (0,0):'center'}

Dictionary Operations

Tuple

Unchangeable collection of objects

tup = (1, 3.12, False, "Hi")

List

Changeable collection of objects

my_collection = [1, 1, 3.12, False, "Hi"]

List Operations

Set

Unordered collection of unique objects

a = {100, 3.12, False, "Bye"}
b = {100, 3.12, "Welcome"}

Set Operations

Indexing

Accessing data from a string, list, or tuple using an element number

my_string[element_number]
my_collection[element_number]
my_tup[element_number]

Slicing

Accessing a subset of data from a string, list, or tuple using element numbers from start to stop -1

my_string[start:stop]
my_collection[start:stop]
my_tup[start:stop]

Comparison Operators

Comparison 0perators compare operands and return a result of true or false

Equal

a == b

Less Than

a < b

Greater Than

a > b

Greater Than or Equal

a >= b

Less Than or Equal

a <= b

Not Equal

a != b

Python Operators

Conditional Operators

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

And

Returns true if both statement a and b are true, otherwise false

a and 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

Loops

For Loops

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 Loops

while statement:

Executes the loop while statement is true

Conditional Statement

if statement_1:
    # Execute of statement_1 is true
if 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 to try to execute
except a:
    # code to execute if there is an error of type a
except b:
    # code to execute if there is an error of type b
except:
    # code to execute if there is any exception that has not been handled
else:
    # code to execute if there is no exception

Error Types

Range

Webscraping

Requests


Functions

Working with Files

Reading a File

Writing to a File

Objects and Classes