Python

General

i = j = 0

a, b = 3, 4
a, b = b, a
print(type(a))
if x >= 10:
    pass
else:
    print('x is less than 10')

Comments

'''
this is a multi
line comment
'''

Equality

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b) # true
print(a is b) # false

Type Checking

a: int

def add(a: float, b: float):
    return a + b

Assertions

x = 'abc'
assert x is not None

x = None
assert x is not None # errors

Data Types

Booleans

Numbers

Lists (Arrays)

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)

print(mylist[1]) # 2
# print(mylist[10]) # error
print(len(mylist)) # 3
test = [1, 2]
# print(test[3]) # IndexError!
if 3 in [1, 3, 5]: print('Number found')

Join and repeat

even_numbers = [2, 4]
odd_numbers = [1, 3]

print(odd_numbers + even_numbers) # [1, 3, 2, 4]
numbers = [1, 2]
print(numbers * 3) # [1, 2, 1, 2, 1, 2]
mylist = ['a', 'b', 'c']
print('-'.join(mylist)) # 'a-b-c'

Slice

string = "Hello world!"

print(string[3:7]) # lo w
print(string[-1]) # !
print(string[-4:]) # rld!
print(string[0:5:2]) # Hlo ([start:stop:step])
print-1]) # !dlrow olleH (reverses the string

Spread

def divide(a, b):
	return a / b

nums_list = [6, 2]

print(divide(*nums_list)) # 3.0

Filter

scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]

def is_A_student(score):
    return score > 75

over_75 = list(filter(is_A_student, scores))
dromes = ("demigod", "rewire", "madam",
          "freer", "anutforajaroftuna", "kiosk")

palindromes = list(filter(lambda word: word == word[::-1], dromes))

Map

my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))
circle_areas = [3.56773, 5.57668, 4.00914, 56.24241, 9.01344, 32.00013]
# `circle_areas` and `range(1, 7)` are the two iterables passed to `round`
result = list(map(round, circle_areas, range(1, 7)))
result = list(map(round, circle_areas, range(1, 3)))
print(result) # [3.6, 5.58]

Zip

my_strings = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
my_numbers = [1, 2, 3, 4, 5]

results = list(zip(my_strings, my_numbers))
print(results) # [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
def my_zip(x, y):
    return (x, y)
results = list(map(my_zip, my_strings, my_numbers))

results = list(map(lambda x, y: (x, y), my_strings, my_numbers))

Reduce

from functools import reduce

numbers = [1, 2, 3, 4, 5]

def custom_sum(first, second):
    return first + second

result = reduce(custom_sum, numbers)
print(result) # 15
resultWithInitial = reduce(custom_sum, numbers, 10)
print(resultWithInitial) # 25

Strings

String functions

string = "Hello world!"

print(len(string)) # 12
print(string.index('o')) # 4
print(string.count('l')) # 3

print(string.upper()) # HELLO WORLD!
print(string.lower()) # hello world!

print(string.startswith('Hello')) # True
print(string.endswith('asdf')) # False

print(string.split(' ')) # ['Hello', 'world!']

String formatting

name = "John"
age = 23
pi = 3.14159
myhex = 255
print("Hello, %s!" % name) # Hello, John!
print("%s is %d years old." % (name, age)) # John is 23 years old.
print("%f %.2f" % (pi, pi)) # 3.141590 3.14
print("%x %X" % (myhex, myhex)) # ff FF

Formatted string literals (f-strings)

a = 5
b = 10

f'{a} + {b} = {a + b}' # '5 + 10 = 15'

Format specifiers

format_spec     ::=  [[fill]align][sign]["z"]["#"]["0"][width]
                     [grouping_option]["." precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" |
                     "G" | "n" | "o" | "s" | "x" | "X" | "%"
Examples
str = 'Hello'
print(f'{str:.>10}') # '.....Hello'
print(f'{str:.<10}') # 'Hello.....'
int = 7
print(f'{int:4}') # '   7'
print(f'{int:04}') # '0007'
float = 300.0
print(f'${float:.2f}') # '$300.00'
bigNumber = 90000
print(f'${bigNumber:,}') # '90,000'
int = 3000
print(f'{int:010,.2f}') # '003,000.00'
str = 'Hello'
width = 10
print(f'{str:.>{width}}') # '.....Hello'

Regular Expressions

import re
pattern = re.compile(r"(\d{1,2}:\d{2}) (AM|PM)")
result = re.search(pattern, "The time is 5:20 PM.")
print(result)
if result:
    print("Groups: %s" % ', '.join(result.groups()))

print(re.search(pattern, "This is a test.")) # Groups: 5:20, PM
print(re.match(pattern, "11:20 AM is when the bus will arrive.")) # Match object
print(re.match(pattern, "The bus will arrive at 11:20 AM.")) # None
print(re.findall(pattern, "The shuttle departs at 8:20 AM, 8:40 AM, and 9:00 AM.")) # [('8:20', 'AM'), ('8:40', 'AM'), ('9:00', 'AM')]

Tuples

x = (1, 2, 3)
print(type(x)) # <class 'tuple'>
print(x[0]) # 1
a, b, c = x
print(b) # 2

Dictionaries (Maps/Objects)

phonebook = {
    "John": 123,
    "Jack": 456,
    "Jill": 789
}

del phonebook['John']

popped = phonebook.pop('Jack')
print(popped) # 456
print(phonebook) # {'Jill': 789}
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
def divide(a, b):
	return a / b

nums_dict = { "b": 2, "a": 6 }

# this works because of named arguments - if we renamed either of the
# keys in the dictionary this would break
print(divide(**nums_dict)) # 3.0

Sets

print(set("one two three two four one".split())) # {'two', 'one', 'four', 'three'}

a = {"Jake", "John", "Eric"}
b = {"John", "Jill"}
print(a.intersection(b)) # {'John'}
print(b.intersection(a)) # {'John'}
print(a.symmetric_difference(b)) # {'Jake', 'Jill', 'Eric'}
print(b.symmetric_difference(a)) # {'Jake', 'Jill', 'Eric'}
print(a.difference(b)) # {'Jake', 'Jill', 'Eric'}
print(b.difference(a)) # {'Jill'}
print(a.union(b)) # {'Jake', 'John', 'Jill', 'Eric'}
print(b.union(a)) # {'Jake', 'John', 'Jill', 'Eric'}

Functions

def sum_two_numbers(a, b=2):
    # b has a default value
    return a + b

print(sum_two_numbers(5)) # 7
number = 1

def increment_number():
    global number
    number += 1

increment_number()
print(sum_two_numbers(b=3, a=4)) # 7
def rest_function(first, second, third, *therest):
    print("The rest... %s" % list(therest))

print(rest_function(1, 2, 3, 4, 5)) # The rest... [4, 5]
def keyword_only_argument(a, *, b):
    return a + b

keyword_only_argument(1, b=2)
keyword_only_argument(1, 2) # errors
def arguments_dict(first, second, third, **options):
    if options.get("action") == "sum":
        print("The sum is: %d" % (first + second + third))
    
    if options.get("number") == "first":
        return first

result = arguments_dict(1, 2, 3, action="sum", number="first")
print("Result: %d" % result) # Result: 1
def next_three_numbers(start):
    return start + 1, start + 2, start + 3

# tuples are a type of their own
xyz = next_three_numbers(5)
print(type(xyz))

Lambdas

lambda x, y: x + y

Closures

def print_msg(number):
    def modifyNumber():
        nonlocal number
        number = 3
    modifyNumber()
    print(number)

print_msg(9) # prints 3 - without nonlocal it would print 9

Decorators

def double_out(old_function):
    def new_function(*args, **kwds):
        return 2 * old_function(*args, **kwds)
    return new_function

def check(old_function):
    def new_function(*args, **kwds):
        for arg in args:
            if arg < 0:
                raise ValueError("Negative Argument")
        return old_function(*args, **kwds)
    return new_function

@double_out
@check
def add(num1, num2):
    return num1 + num2
# calling this is the same as calling double_out(check(add2))(num1, num2)

try:
    print(add(-2, 3))
except ValueError:
    print("Caught ValueError")

Generators

import random

def lottery():
    # returns 6 numbers between 1 and 40
    for _ in range(6):
        yield random.randint(1, 40)

    # returns a 7th number between 1 and 15
    yield random.randint(1, 15)

for random_number in lottery():
    print("And the next number is... %d!" % (random_number))

Flow Control

if and Comparisons

name = "John"
age = 23

if name == "John" and age == 23:
    print("Your name is John, and you are also 23 years old.")

if name == "John" or name == "Rick":
    print("Your name is either John or Rick.")

# one-line shorthand
if name == "John": print("Hello John!")

if name in ["John", "Rick"]:
    print("Your name is either John or Rick.")
elif name == "Bob":
    print("Your name is Bob.")
else:
    print("Your name is not John, Rick, or Bob.")

print(bool(""), bool(0), bool([]), bool({})) # all False

print(not False) # True

Ternary conditionals

beverage = 'coffee' if is_morning() else 'water'

for

Sequences

for x in mylist:
    print(x)
for i, x in enumerate(mylist):
    print('The value at %d is %s' % (i, x))

Ranges

for x in range(5):
    print(x) # prints 0, 1, 2, 3, 4

for x in range(3, 6):
    print(x) # prints 3, 4, 5

for x in range(3, 8, 2):
    print(x) # prints 3, 5, 7

for x in range(5, 0, -1):
    print(x) # prints 5, 4, 3, 2, 1
list = ['e', 'd', 'c', 'b', 'a']

for x in range(len(list) - 1, -1, -1):
    print(list[x]) # prints a, b, c, d, e

List Comprehensions

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()

word_lengths = [len(word) for word in words if word != "the"]
print(word_lengths) # [5, 5, 3, 5, 4, 4, 3]
word_lengths = []
for word in words:
    if word != "the":
        word_lengths.append(len(word))
print(word_lengths)

while

count = 0
while count < 5:
    print(count)
    count += 1

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

count = 0
    while count < 5:
        print(count)
        count += 1
    else:
        # executes if the condition fails, but not if break is used
        print("count value reached %d" % count)

Exception Handling

the_list = ["a", "b", "c", "d"]

for i in range(5):
    try:
        print(the_list[i])
    except IndexError:
        print("Index %d does not exist" % i)
    except:
        # will catch anything not already caught
        print("Unknown error")

Classes

class MyClass:
    variable = "apple"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
myobjecty = MyClass()

myobjectx.variable = "banana"

print(myobjectx.variable) # banana
print(myobjecty.variable) # apple
myobjectx.function() # prints "This is a message inside the class."

isinstance(myobjectx, MyClass) # True

Modules and Packages

# imports into variable `re`
import re

# imports into variable `regular_expressions`
import re as regular_expressions

# imports `compile` directly into current namespace
from re import compile

# imports all objects from `re` into the current namespace
from re import *
help('modules')
print(dir(re))
import re

help(re)
help(re.compile)

Built-in modules

enum

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    CRIMSON = 1 # this is an alias for RED since they have the same value

Color.RED is Color(1) # True
Color.RED is Color['RED'] # True
Color.RED is Color.CRIMSON # True

print(Color.BLUE) # Color.BLUE
print(Color.BLUE.name) # BLUE
print(Color.BLUE.value) # 3

# note: aliases aren't included when iterating
print(list(Color)) # [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])

Color = Enum('Color', { 'RED': 'red', 'GREEN': 'green', 'BLUE': 'blue' })
from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()
from enum import Enum

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7
    #
    @classmethod
    def from_date(cls, date):
        return cls(date.isoweekday())

from datetime import date
print(Weekday.from_date(date.today())) # prints the enum member for the current day
from enum import Flag
class Weekday(Flag):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 4
    THURSDAY = 8
    FRIDAY = 16
    SATURDAY = 32
    SUNDAY = 64

weekend = Weekday.SATURDAY | Weekday.SUNDAY

for day in weekend:
    print(day) # prints Weekday.SATURDAY and Weekday.SUNDAY

time

import time

# Unix timestamp, float of seconds since the epoch
time.time()

random

import random

random.random() # random float between 0 and 1
random.uniform(a, b) # random float between a and b (inclusive)
random.randint(a, b) # random int between a and b (inclusive)

random.choice(seq) # random item from the sequence seq