Notes

Formatted Strings

shopping_list = ['bread','milk','eggs']
print(','.join(shopping_list))
# Comma Thousands Separator
 print('{:,}'.format(1234567890))
  '1,234,567,890'

# Date and Time
d = datetime.datetime(2020, 7, 4, 12, 15, 58)
print('{:%Y-%m-%d %H:%M:%S}'.format(d))
'2020-07-04 12:15:58'

# Percentage
points = 190
total = 220
print('Correct answers: {:.2%}'.format(points/total))
Correct answers: 86.36%

# Data Tables
width=8
print(' decimal      hex   binary')
print('-'*27)
for num in range(1,16):
    for base in 'dXb':
        print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
    print()

Getting Input from the Command Line


Scripts vs Programs


Structured Data


Built In Data Types

empty_list = []
departments = ['HR','Development','Sales','Finance','IT','Customer Support']

# You can instantiate
specials = list()

# Test if a value is in a list.
print(1 in [1, 2, 3]) #> True
print(4 in [1, 2, 3]) #> False
# Instantiated with parentheses
time_blocks = ('AM','PM')

# Sometimes instantiated without
colors = 'red','blue','green'
numbers = 1, 2, 3

# Tuple() built in can be used to convert other data into a tuple
tuple('abc')        # returns ('a', 'b', 'c')
tuple([1,2,3])      # returns (1, 2, 3)
range(5)            # [0, 1, 2, 3, 4]
range(1,5)          # [1, 2, 3, 4]
range(0, 25, 5)     # [0, 5, 10, 15, 20]
range(0)            # [ ]
for let (i = 0; i < 5; i++)
for let (i = 1; i < 5; i++)
for let (i = 0; i < 25; i+=5)
for let(i = 0; i = 0; i++)
a = {'one':1, 'two':2, 'three':3}
b = dict(one=1, two=2, three=3)
c = dict([('two', 2), ('one', 1), ('three', 3)])

a, b, and c are all equal

school_bag = {'book','paper','pencil','pencil','book','book','book','eraser'}
print(school_bag)

# Also can use set constructor to automatically put it into a set.
letters = set('abracadabra')
print(letters)

Built-In Functions

Functions using iterables

quarters = ['First', 'Second', 'Third', 'Fourth']
print(enumerate(quarters))
print(enumerate(quarters, start=1))

# (0, 'First'), (1, 'Second'), (2, 'Third'), (3, 'Fourth')
# (1, 'First'), (2, 'Second'), (3, 'Third'), (4, 'Fourth')

Functions that analyze iterables

Working with dictionaries

Working with sets

a = {1, 2, 3}
b = {2, 4, 6}
print(a | b)        # => {1, 2, 3, 4, 6}
a = {1, 2, 3}
b = {2, 4, 6}
print(a & b)        # => {2}
a = {1, 2, 3}
b = {2, 4, 6}
print(a - b)        # => {1, 3}
print(b - a)        # => {4, 6}
print(a ^ b)        # => {1, 3, 4, 6}

For Statements

print('My name is')
for i in range(5):
   print('Carlita Cinco (' + str(i) + ')')

total = 0
for num in range(101):
    total += num
print(total)
for c in ['a', 'b', 'c']:
    print(c)

lst = [0, 1, 2, 3]
for i in lst:
    print(i)
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
    print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
l = [[1, 2], [3, 4], [5, 6]]
for a, b in l:
    print(a, ', ', b)

# Prints 1, 2
# Prints 3, 4
# Prints 5, 6
spam = {'color': 'red', 'age': 42}
for v in spam.values():
    print(v)

# Prints red
# Prints 42

for k in spam.keys():
    print(k)

# Prints color
# Prints age
# Getting tuples
for i in spam.items():
    print(i)

# Prints ('color', 'red')
# Prints ('age', 42)


# Destructuring to values
for k, v in spam.items():
    print('Key: ' + k + ' Value: ' + str(v))

# Prints Key: age Value: 42
# Prints Key: color Value: red
for c in "abcdefg":
    print(c)

More On Functions

def add(a, b, *args):
    total = a + b;
    for n in args:
        total += n
    return total

add(1, 2)  # Returns 3

add(2, 3, 4, 5) # Returns 14
def print_names_and_countries(greeting, **kwargs):
    for k, v in kwargs.items():
        print(greeting, k, "from", v)

print_names_and_countries("Hi",
                          Monica="Sweden",
                          Charles="British Virgin Islands",
                          Carlo="Portugal")
# Prints
# Hi Monica from Sweden
# Hi Charles from British Virgin Islands
# Hi Carlo from Portugal
def example(arg_1, arg_2, *args, **kwargs):
  pass

def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blowfish", **kwargs):
  pass

Importing in Python

Terms

from urllib.request import (
  HTTPDefaultErrorHandler as ErrorHandler,
  HTTPRedirectHandler as RedirectHandler,
  Request,
  pathname2url,
  url2pathname,
  urlopen,
)

Watching Out for Python 2