Nov 04, 2018 ▪ 21 min read (~3 pages) Computer Science Updated on Jan 03, 2023

A Python Primer and Cheat Sheet

1. Introduction

Python program structure (build and run with $ python <filename>.py).

#!/usr/bin/python

def main():
    # do something
    return

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

Handling 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

2. Arithmetic Operators

Basic arithmetic operators.

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

Power operator.

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

Be aware of this common division error.

30 / 20
# 1
30.0 / 20.0
# 1.5

Integer divison (quotient).

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

Modulo (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

3. Variables

Basic variables.

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

Using type built-in.

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

4. Strings

4.1 Indexing

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

4.2 Operations

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 string

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

5. Data structures

5.1 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

Length of lists.

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']

5.2 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')

5.3 Dictionaries

Dictionaries are key-value pairs.

dict = {
    'Adam': ['[email protected]', 2445055],
    'Bard': '[email protected]'
}
dict
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}
dict['Adam']
# ['[email protected]', 2445055]
dict['Adam'][1]
# 2445055

Dictionaries are mutable.

dict['Bard'] = '[email protected]'
dict
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}

Add and remove items.

dict['Cole'] = '[email protected]'
dict
# {'Cole': '[email protected]', 'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}
del dict['Cole']
# {'Adam': ['[email protected]', 2445055], 'Bard': '[email protected]'}
'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'}

5.4 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 and remove from 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)

6. Conditionals

6.1 If-Else

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

Single line expressions

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

6.2 Logical Operators

Booleans.

T = True
F = False
T or F
# True
T and (T and F)
# False
not T
# False
not (not T)
# True

Numbers.

1 == 2
# False
1 != 2
# True

7. Loops

7.1 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)

7.2 While

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

8. Functions

Functions are defined with def keyword.

def function(arg):
    # do something
    return

Power operator as function.

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.

9. Classes

Classes are defined with class keyword.

class Money (object):
    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency
    def __str__(self):
        return str(self.amount) + ' ' + self.currency

Create new instance of class.

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

Print use __str__.

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)

10. Files

Reading from files.

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

Read lines from text-file.

with open('path/to/file.txt', 'r') as file:
    for line in file.readlines():
        # do something

Write to text-file.

with open('path/to/file.txt', 'w') as file:
    file.write('This is some text to write.')

11. Modules

11.1 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

11.2 Math

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

Mathematical operations.

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