This post is more than two years old and may contain outdated information.

A Python Primer and Cheat Sheet

June 8, 2018

In this post:


Introduction #

Hello Python #

Build and run with python <filename>.py.

#!/usr/bin/python

def main():
    print("hello python")

if (__name__ == "__main__"):
    main()
    # hello python

Error handling #

try:
    x = 1 / 0 # ops!

except ZeroDivisionError:
    print("error: cannot divide by zero")
    # do something
    pass

# general exception

except Exception as e:
    print(f"error: ${e}")
    # do something
    pass

finally:
    # do something
    pass

Arithmetic Operators #

print(12 + 2 * (40 / 4) + 10)
# 42

# power
print(10 ** 2)
# 100

# floating-point conversion
print(12.0 + (10 + 20))
# 42.0

# integer divison
print(42 // 40)
# 1

# modulo
print(42 % 40)
# 2

# built-ins
print(abs(-42))
# 42
print(sum([1, 2, 3, 4]))
# 10
print(min(1, 2, 3, 4))
# 1
print(max(1, 2, 3, 4))
# 4

# rounding value
print(round(42.42))
# 42
print(round(42.42, 1))
# 42.4

Variables #

x = 6
y = "String"
z = 1.05
a = x

print(type(x))
# <class 'int'>
print(type(y))
# <class 'str'>
print(type(z))
# <class 'float'>
print(type(a))
# <class 'int'>

x = a = 6
y, z = "String", 1.05

print(x, y, z, a)
# 6 String 1.05 6

# list assignment
d, t, v = [230, 45, 12]
print(d, t, v)
# 230 45 12

# string assignment
a, b, c, d = "100B"
print(a, b, c, d)
# 1 0 0 B

string = "100B"
print(string[:3])
# 100
print(string[3:])
# B

# delete
del x
print(x)
# NameError: name 'x' is not defined

Strings #

string = "proton neutron"

Indexing #

print(string[:])
# proton neutron
print(string[:2])
# pr
print(string[-2:])
# on
print(string[1:3])
# ro

# reverse
print(string[::-1])
# notorp

# skip every second character
print(string[0:-1:2])
# poo

Built-ins #

# built-ins
print(string.capitalize())
# Proton neutron
print(string.title())
# Proton Neutron
print(string.upper())
# PROTON NEUTRON
print(string.lower())
# proton neutron
print(string.center(20, '.'))
# ...proton neutron...

# conditionals
print(string.isdigit())
# False
print(string.islower())
# True
print(string.isupper())
# False

Counting and finding letters in text #

print(string.count('p', 0, len(string)))
# 1
print(string.find('t', 1, len(string)))
# 3

Removing whitespace from string #

string = "    some text    "

print(string.lstrip())
# 'some text    '
print(string.rstrip())
# '    some text'
print(string.strip())
# 'some text'

Data structures #

Lists #

Lists are mutable.

lst_one = ["remove", "random"]
lst_two = [200, -2, [1.0, 0.0]]

lst_one[0] = "ADD"

print(lst_one)
# ['ADD', 'RANDOM']
print(lst_one[1])
# RANDOM

# length
print(len(lst_one))
# 2

# concatenate
lst = lst_one + lst_two
print(lst)
# ['ADD', 'RANDOM', 200, -2, [1.0, 0.0]]

# append
lst.append(None)
print(lst)
# ['ADD', 'random', 200, -2, [1.0, 0.0], None]

# convert to string before sorting
print(sorted(list(map(str,lst))))
# ['-2', '200', 'ADD', 'None', '[1.0, 0.0]', 'random']

# string to list
print(list("100B"))
# ['1', '0', '0', 'B']

Tuples #

Tuples are immutable.

tuple_one = (1.0, "String", 4)
tuple_two = ("Alpha", "Bravo", (1, 0))

print(tuple_one)
# (1.0, 'String', 4)
print(tuple_two)
# ('Alpha', 'Bravo', (1, 0))
print(tuple_two[2][1])
# 0

# concatenate
tuples = tuple_one + tuple_two
print(tuples)
# (1.0, 'String', 4, 'Alpha', 'Bravo', (1, 0))

# list to tuple
print(tuple([100, 'B']))
# (100, 'B')

Dictionaries #

Dictionaries are hash tables, i.e. key:value pairs.

dct = {
    "Adam": ["[email protected]", 2445055],
    "Bard": "[email protected]"
}

print(dct)
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}
print(dct["Adam"])
# ['[email protected]', 2445055]
print(dct["Adam"][1])
# 2445055

# update value
dct["Bard"] = "[email protected]"
print(dct)
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}

# add key:value pair
dct["Cole"] = "[email protected]"
print(dct)
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]', 'Cole': '[email protected]'}

# remove key:value pair
del dct["Cole"]

print("Cole" in dct)
# False
print("Adam" in dct)
# True

# create dictionary from a list of tuples
dct_list_tuples = dict([(1, "x"), (2, "y"), (3, "z")])
print(dct_list_tuples)
# {1: 'x', 2: 'y', 3: 'z'}

Sets #

Sets are unordered collections.

my_set = {1.0, 10, "String", (1, 0, 1, 0)}

print(my_set)
# {'String', 1.0, 10, (1, 0, 1, 0)}
print("String" in my_set)
# True

# add
my_set.add("Python")
print(my_set)
# {1.0, 'String', 10, (1, 0, 1, 0), 'Python'}

# remove
my_set.remove("String")
print(my_set)
# {1.0, 10, (1, 0, 1, 0), 'Python'}

# set operations
set_one = {1, 2, 3}
set_two = {3, 4, 5}

# union
print(set_one | set_two)
# {1, 2, 3, 4, 5}

# Intersection
print(set_one & set_two)
# {3}

# Difference
print(set_one - set_two)
# {1, 2}

# Symmetric difference
print(set_one ^ set_two)
# {1, 2, 4, 5}

# subset and superset
set_a = {1, 2}
set_b = {1, 2}
set_c = {1, 2, 3, 4, 5}

# Strict subset
print(set_a < set_b)
# False

# Subset
print(set_a <= set_b)
# True

Conditionals #

a = 1.0
b = 5.0

if (a < 1.0):
    # do something
    pass

elif (a == 1.0):
    # do something
    pass

else:
    # do something
    pass

# single line expression
c = (a / b) if a != 0 else a
print(c)
# 0.2

Logical Operators #

TRUE = True
FALSE = False

print(TRUE or FALSE)
# True
print(TRUE and (TRUE and FALSE))
# False

print(not TRUE)
# False
print(not (not TRUE))
# True

print(1 == 2)
# False
print(1 != 2)
# True

Loops #

numbers = [1, 2, 3, 4]

for number in numbers:
    # do something
    pass

# nested
for i in range(10):
    for j in range(10):
        # do something
        pass

# iterating dictionaries
dict = { 'a': 1, 'b': 2 }

for key in dict.keys(): print(key)
# a
# b

for value in dict.values(): print(value)
# 1
# 2

for key, value in dict.items(): print(key, value)
# a 1
# b 2

# while

x = 0
while (x < 10):
    # do something
    x += 1

print(x)
# 10

Functions #

def power(base, x = 1):
    """base to the x-th power"""

    i = 0
    while i < x - 1:
        base += base
        i += 1

    return base

print(power(2, 8))
# 256
print(power.__doc__)
# base to the x-th power

print(power(2))
# 2

Classes #

# class
class Money(object):
    # constructor
    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency
    # string representation
    def __str__(self):
        return f"{self.amount} {self.currency}"

# create new instance of class
money = Money(220, "EUR")
money.amount, money.currency

print(money)
# 220 EUR
print(money.amount, money.currency)
# 220 EUR

# subclass
class VirtualMoney(Money):
    def __init__(self, date):
        self.date = date
        # inherits amount and currency from Money

    # override string representation
    def __str__(self):
        return f"{self.amount} {self.currency} (expire: {self.date})"

# create new instance of subclass
virtual_money = VirtualMoney("2018-12-31")
virtual_money.amount = 20
virtual_money.currency = "V-Bucks"

print(virtual_money)
# 20 V-Bucks (expire: 2018-12-31)

Files #

# write to file
with open("_file.txt", "w") as file:
    file.write("this is some text to write\nanother line")

# read from file
text = ""
with open("_file.txt", "r") as file:
    text = file.read()

# or
text = open("_file.txt", "r").read()
print(text)
# this is some text to write
# another line

# read lines
with open("_file.txt", "r") as file:
    for line in file.readlines():
        # do something
        pass

Modules #

Date and time #

from datetime import datetime
from datetime import timedelta

now = datetime.now()
print(now)
# 2018-06-15 18:23:51.500993

future = now + timedelta(12)
print(future)
# 2018-06-27 18:23:59.351647

print(now.year)
# 2018
print(now.month)
# 6
print(now.day)
# 15
print(now.hour)
# 18
print(now.minute)
# 23

# difference between dates
difference = future - now
print(difference.days)
# 12

Math #

import math

# constants
print(math.pi)
# 3.14159265359
print(math.e)
# 2.71828182846

# numerical operations
print(math.floor(2.945))
# 2
print(math.trunc(2.945))
# 2
print(math.factorial(5))
# 120
print(math.exp(1))
# 2.71828182846
print(math.sqrt(16))
# 4.0