Python-Cheat-Sheet
Python-Cheat-Sheet
Each section is designed to give you a concise, actionable Functions Dates and Times
overview of Python’s core functionality in the context of real- DEFINITION, arguments, RETURN DATETIME, DATE, TIME,
Strings
FORMATTING, TRANSFORMING,
CLEANING
Comments # print(1 + 2)
We call the sequence of Operation
x += 2 # Addition
Augmented assignment
characters that follows the
Shortcuts operators: used to update a
print(5 * 10)
x -= 2 # Subtraction
value or variable.
Multiplication
print(type(x)) # list
30 * 2 # output: 60
print(type(y)) # integer
print(type('4')) # string
20 / 3 # output: 6.666666666666667 Division
Initializing
cost = 20
Variable names can only
Variables total_cost = 20 + 2**5
contain letters, numbers, and
underscores―they cannot
currency = 'USD'
Updating
x = 30
To update a variable, use the
Variables print(x) # 30 is printed
print(x) # 50 is printed
Syntax for How to use Explained Syntax for How to use Explained
Lists Creating a list and appending List of Lists Opening a dataset file and
a_list = [1, 2]
from csv import reader
apps_data = list(read_file)
Creating a list of data points;
row_1 = ['Facebook', 0.0, 'USD', 2974676]
list using each item’s index row_3 = ['Clash', 0.0, 'USD', 2130805, 4.5]
indexing begins at 0
Negative
print(row_1[-1]) # output: 2974676
third_row_last_element = lists[-2][4]
first_two_rows = lists[:2]
print(row_3[:2])
specific elements from a
omitted, the slice begins at all_but_first_row = lists[1:]
print(row_3[1:4])
select from the start, and
end is omitted, it continues # output: ['Instagram', 'USD', 2161558]
print(row_3[3:])
the end
# output: [1.99, 'USD']
# output: [2130805, 4.5]
Dictionaries
# First way
frequency_table = {}
counting occurrences of
# Second way
way) not
frequency_table[a_data_point] = 1
data_sizes dictionary
'key_5' in dictionary # outputs False
data_size = float(row[2])
data_sizes['0 - 10 MB'] += 1
dictionary['key_1'] += 600
dictionary['key_2'] = 400
print(dictionary)
data_sizes['500 MB +'] += 1
Syntax for How to use Explained Syntax for How to use Explained
Basic
def square(number):
return a - b
Helper
Functions
def find_sum(lst):
Define helper functions to
print(add(3 + 14)) # output: 17 a_sum = 0
find the sum and length of a
for element in lst:
list; the mean function reuses
This function creates a a_sum += float(element)
these to calculate the
def freq_table(list_of_lists, index):
average by dividing the sum
frequency table for any given return a_sum
frequency_table = {}
by the length
column index of the
for row in list_of_lists:
value = row[index]
length = 0
if value in frequency_table:
frequency_table[value] += 1
length += 1
else:
return length
frequency_table[value] = 1
return frequency_table
def mean(lst):
Syntax for How to use Explained Syntax for How to use Explained
Multiple
Define a function that Multiple
This function uses multiple
def price(item, cost):
def sum_or_difference(a, b, return_sum=True):
return a + b
depending on the
print(price("chair", 40.99))
return a - b
return_sum argument,
# output: 'The chair costs $40.99.'
which defaults to True
print(sum_or_difference(10, 7))
# output: 17
Returning
This function returns
def sum_and_difference(a, b):
Syntax for How to use Explained Syntax for How to use Explained
Formatting
continents = "France is in {} and China is
million".format(name="Brazil", pop=209)
from a string by replacing
names periods, and exclamation marks!"
commas as a thousand
{:,}".format("India", 1324000000)
Split a string into a list of
separator by position split_on_dash = "1980-12-08".split("-")
${:,.2f}".format(12345.678)
indices default to the start or
places for currency formatting # This
# Your bank balance is $12,345.68 end of the string
Syntax for How to use Explained Syntax for How to use Explained
rating_sum = 0
Convert a column of strings if True:
Both conditions evaluate to
for row in apps_data[1:]:
(row[7]) in a list of lists print(1)
True, so all print statements
rating = float(row[7])
(apps_data) to a float and if 1 == 1:
are executed
rating_sum = rating_sum + rating keep a running sum of print(2)
ratings print(3)
apps_names = []
Append values with each
for row in apps_data[1:]:
iteration of a for loop if True:
Only the blocks with True
name = row[1]
print('First Output')
conditions are executed, so
apps_names.append(name) if False:
the second print statement is
print('Second Output')
skipped
if True:
Conditional
price = 0
Use comparison operators to print('Third Output')
Statements print(price == 0) # Outputs True
check if a value equals
print(price == 2) # Outputs False another, returning True or
False Else
if False:
The code in the else clause
Statements print(1)
is always executed when
print('Games' == 'Music') # Outputs False
Compare strings and lists else:
the if statement is False
print('Games' != 'Music') # Outputs True
using == for equality and != print('The condition above was false.')
print([1,2,3] == [1,2,3]) # Outputs True
for inequality, returning True
print([1,2,3] == [1,2,3,4]) # Outputs False or False
Syntax for How to use Explained Syntax for How to use Explained
Else
if "car" in "carpet":
if or else block
print("The substring was not found.") Instantiate an object from
Instantiating
class MyClass:
name followed by
Elif
The elif statement allows mc_1 = MyClass()
if 3 == 1:
parentheses
Statements for multiple conditions to be
print('3 does not equal 1.')
executed arguments
false.') # mc_2.attribute is set to "arg_1"
Defining
Define a method within the
class MyClass:
Multiple
if 3 > 1 and 'data' == 'data':
if 10 < 20 or 4 >= 5:
Importing
Import the module, requiring Creating
Convert a datetime object into
import datetime
eg_2_str = eg_2.strftime(
Datetime
the full path to access Datetime
a formatted string; the "f "
current_time = datetime.datetime.now() "%B %d, %Y at %I:%M %p")
Examples functions or classes Objects stands for formatting
# "August 15, 1990 at 08:45 AM"
Import the module with alias
import datetime as dt
Create a time object that includes
current_time = dt.datetime.now()
dt for shorter references, a eg_3 = dt.time(hour=5, minute=23,
Creating
Create a datetime object with eg_2_time = eg_2.time()
Extract the time component
import datetime as dt
Datetime
both date (March 13, 1985) and from a datetime object that
eg_1 = dt.datetime(1985, 3, 13, 14, 30, 45) # 08:45:30
Objects time (14:30:45) components contains both date and time
using the .time() method
from datetime import datetime as dt
Convert a formatted string
into a datetime object; the
eg_2 = dt.strptime("15/08/1990 08:45:30",