Michael Sjoeberg

A Python Primer and Cheat Sheet.

# Notes

Execute code.

#!/usr/bin/python

def main():
    # do something

    return

if (__name__ == "__main__"):
    main()

Build and run with: $ python filename.py.

Handle exceptions.

try:
    # do something

except ZeroDivisionError:
    print ('Cannot divide with zero.')
    # do something

except Exception as e:
    print ('Error: ' + str(e))
    # do something

finally:
    # do something

# Arithmetic Operators

10 + 20                 # 30
20 - 10                 # 10
10 * 20                 # 200
20 / 10                 # 2
10 ** 2                 # 100

Automatic floating point conversion.

10.0 + (10 + 20)        # 40.0
20.0 - (10 + 10)        # 0.0
10.0 * (10 * 2)         # 200.0

Common division error.

30 / 20                 # 1
30.0 / 20.0             # 1.5

Integer divison, or quotient.

20.0 // 20.0            # 1.0
30.0 // 20.0            # 1.0
40.0 // 20.0            # 2.0

Modulo, or remainder.

12.5 % 10.0             # 2.5
10.0 % 20.0             # 10.0

Built in numerical operations.

abs(-20)                # 20
sum([1, 2, 3, 4])       # 10
min(1, 2, 3, 4)         # 1
max(1, 2, 3, 4)         # 4

Rounding values.

round(2.945)            # 3.0
round(2.495)            # 2.0
round(2.945, 2)         # 2.94

See Math for more.

# Variables

x = 6
y = 'String'
z = 1.05
a = x
x, y, z, a                  # (6, 'String', 1.05, 6)
type(x)                     # int
type(y)                     # str
type(z)                     # float
type(a)                     # int

Multiple assignments.

x = a = 6

y, z = 'String', 1.05
x, y, z, a                  # (6, 'String', 1.05, 6)

List assignments.

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

String assignments.

a, b, c, d = '100B'         # ('1', '0', '0', 'B')
string = '100B'

number = string[:3]
letter = string[3:]
number, letter              # ('100', 'B')

Delete a variable.

del n
n                           # NameError: name 'n' is not defined

# String Indexing

string = 'proton'
string[:]               # proton
string[:2]              # pr
string[-2:]             # on
string[1:3]             # ro

Reverse a string.

string[::-1]            # notorp

Skip every second character.

string[0:-1:2]          # poo

# String Operations

string = 'proton neutron'
string.capitalize()         # Proton neutron
string.title()              # Proton Neutron
string.upper()              # PROTON NEUTRON
string.lower()              # proton neutron
string.center(20, '.')      # ...proton neutron...
string.isdigit()            # False
string.islower()            # True
string.isupper()            # False

Counting and finding letters in text.

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

Removing whitespace from a string.

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

# Data Structures

# Lists

Lists are mutable.

list_one = ['REMOVE', 'RANDOM']
list_two = [200, -2, [1.0, 0.0]]
list_one[0] = 'ADD'         # ['ADD', 'RANDOM']
list_one[1]                 # RANDOM
len(list_one)               # 2
len(list_two)               # 3

Concatenate lists.

list = list_one + list_two          # ['ADD', 'RANDOM', 200, -2, [1.0, 0.0]]

List operations.

list.append('NULL')                 # ['ADD', 'RANDOM', 200, -2, [1.0, 0.0], 'NULL']
list.sort()                         # [-2, 200, [1.0, 0.0], 'ADD', 'NULL', 'RANDOM']

Create list from a string.

list_string = list('100B')          # ['1', '0', '0', 'B']

# Tuples

Tuples are immutable.

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

Concatenate tuples.

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

Create tuple from a list.

tuple_list = tuple([100, 'B'])      # (100, 'B')

# Dictionaries

Dictionaries, or hash tables, with key:value pairs.

dict = {'Adam': ['adam@email.com', 2445055],
        'Bard': 'bard@email.com'}
dict                    # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@email.com'}
dict['Adam']            # ['adam@email.com', 2445055]
dict['Adam'][1]         # 2445055
dict['Bard'] = 'bard@anotheremail.com'
dict                    # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}

Add and remove key:value pairs.

dict['Cole'] = 'cole@email.com'
dict                    # {'Cole': 'cole@email.com', 'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}
del dict['Cole']        # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}
'Adam' in dict          # True

Create dictionary from a list of tuples.

dict_list_tuples = dict([(1, "x"), (2, "y"), (3, "z")])
dict_list_tuples        # {1: 'x', 2: 'y', 3: 'z'}

# Sets

Sets are unordered collections.

set = {1.0, 10, 'String', (1, 0, 1, 0)}
set                     # set([(1, 0, 1, 0), 10, 'String', 1.0])
'String' in set         # True
'Java' in set           # False

Add to a set.

set.add('Python')       # set(['Python', (1, 0, 1, 0), 10, 'String', 1.0])
set.remove('Python')    # set([(1, 0, 1, 0), 10, 'String', 1.0])

Set operations.

set_one = {1, 2, 3}     # set([1, 2, 3])
set_two = {3, 4, 5}     # set([3, 4, 5])
set_one | set_two       # set([1, 2, 3, 4, 5])      (Union)
set_one & set_two       # set([3])                  (Intersection)
set_one - set_two       # set([1, 2])               (Difference)
set_one ^ set_two       # set([1, 2, 4, 5])         (Symmetric difference)

Subset and superset.

set_a = {1, 2}
set_b = {1, 2}
set_c = {1, 2, 3, 4, 5}
set_a < set_b           # False                     (Strict subset)
set_a <= set_b          # True                      (Subset)
set_c > set_a           # True                      (Strict superset)

# Conditionals

# If-Else Statements

a = 1.0
b = 5.0
if (a < 1.0):
    # do something

elif (a == 1.0):
    # do something

else:
    # do something

Single line expression.

c = (a / b) if a != 0 else a    # 0.2

# Logical Operators

T = True
F = False
T or F                          # True
T and (T and F)                 # False
not T                           # False
not (not T)                     # True
1 == 2                          # False
1 != 2                          # True

# Loops

# For

numbers = [1, 2, 3, 4]
for number in numbers:
    # do something

Nested for loops.

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

Using for loops and dictionaries.

dict = {'Alpha': 1, 'Beta': 2}
for key in dict.keys():
    print (key)                     # Alpha Beta

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

for key, value in dict.items():
    print (key, value)              # ('Alpha', 1) ('Beta', 2)

# While

a = 0
b = 5
while (a < b):
    # do something

    a += 1
print (a)                           # 5

# Functions

def function(arg):
    # do something

    return
def power(base, x):

    return base ** x
power(2, 3)                 # 8

Default arguments.

def power(base, x = 3):

    return base ** x
power(2)                    # 8

Multiple return values.

def power(base, x):
    result = base ** x

    return result, base
result, base = power(2, 3)      # (8, 2)

Docstrings.

def function(arg):
    '''This is a docstring.'''

    return
print (function.__doc__)        # This is a docstring.

# Classes

class Money (object):

    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency

    def __str__(self):
        return str(self.amount) + ' ' + self.currency

Create a new instance of class.

money = Money(220, 'EUR') 
money.amount, money.currency        # (220, 'EUR')
print(money)                        # 220 EUR

Subclasses.

class VirtualMoney (Money):

    def __init__(self, date):
        self.date = date

    def __str__(self):
        return str(self.amount) + ' ' + self.currency + ' (use before ' + self.date + ')'
virtual_money = VirtualMoney('2018-12-31')
virtual_money.amount = 20
virtual_money.currency = 'DIS'
virtual_money                       # 20 DIS (use before 2018-12-31)

# Files

Read from a file.

with open('path/to/file', 'r') as file:
    file.read()
content = open('path/to/file', 'r').read()

Read lines from a text-file.

with open('path/to/file.txt', 'r') as file:

    for line in file.readlines():
        # do something

Write data to a text-file.

with open('path/to/file.txt', 'w') as file:

    file.write('This is some text to write.')

# Modules

# Datetime

from datetime import datetime
from datetime import timedelta
now = datetime.now()            # 2018-06-15 18:23:51.500993
future = now + timedelta(12)    # 2018-06-27 18:23:59.351647
now.year                        # 2018
now.month                       # 6
now.day                         # 15
now.hour                        # 18
now.minute                      # 23

Difference between dates.

difference = future - now
difference                      # 12 days, 0:00:00
difference.days                 # 12

# Math

import math
math.pi                         # 3.14159265359
math.e                          # 2.71828182846

Numerical operations, more at https://docs.python.org/2/library/math.html.

math.floor(2.945)               # 2.0
math.trunc(2.945)               # 2
math.factorial(5)               # 120
math.exp(1)                     # 2.71828182846
math.sqrt(16)                   # 4.0
math.sin(4 * math.pi / 180)     # 0.0697564737441