Python BootCamp

Updated 30 June 2017

1. Installation

Installing OSX

Open Terminal

# install python
brew update
brew install python3
# install and upgrade some essential packages
pip3 install --upgrade pip setuptools pipenv
# optionally install some handy development tools
pip3 install flake8 autopep8 ipython cookiecutter

# data tools!
pip3 install jupyter pandas

Installing Windows

Using Portable Versions

alt text

2. Introduction to Python

Why Python

  • Easy

  • Fast

  • Web/Data Science/Bots/Scraping

Python Slow?

Python 3 or 2?




alt text

3. Strings

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Because text is such a common form of data that we use in everyday life, the string data type is a very important building block of programming.

Variable Names

Valid Invalid Why Invalid
my_int my-int Hyphens are not permitted
int4 4int Cannot begin with a number
MY_INT $MY_INT Cannot use symbols other than _
another_int another int Cannot be more than one word

3.1 Creating Strings


Comments in Python begin with a hash mark (#) and whitespace character and continue to the end of the line.

Because comments do not execute, when you run a program you will not see any indication of the comment there. Comments are in the source code for humans to read, not for computers to execute.

# Comment! This is Ignored!
""" Multiline strings can be written
    using three "s, and are often used
    as comments
' Multiline strings can be written\n    using three "s, and are often used\n    as comments\n'
# Strings are created with " or '
string = 'hello'
# Longer Strings!
story = """There once lived in a town of Persia two brothers, one named Cassim and the other Ali Baba. Their father divided a small inheritance equally between them. Cassim married a very rich wife, and became a wealthy merchant. Ali Baba married a woman as poor as himself, and lived by cutting wood, and bringing it upon three asses into the town to sell."""
'There once lived in a town of Persia two brothers, one named Cassim and the other Ali Baba. Their father divided a small inheritance equally between them. Cassim married a very rich wife, and became a wealthy merchant. Ali Baba married a woman as poor as himself, and lived by cutting wood, and bringing it upon three asses into the town to sell.'
# A Line break is a string!
string = """ hello 

' hello \nthere'

3.2 Joining Strings

# Joining strings
string = 'hello ' + 'world'
string = string + "!"
'hello world!'
# Same result as above (Shortcut)
string = 'hello ' + 'world'
string += "!"
'hello world!'

3.3 Indexing (selecting stuff)

alt text

'hello world!'
string[0] # starts from 0
string[:4] # everything from 0 until 4 not inclusive
string[4:] # 4 till the end
'o world!'
string[:-1] # everything until last element not inclusive
'hello world'

3.4 String Methods (Actions)

Python has several built-in functions associated with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Python programming language and are readily available for us to use.

'hello world!'

The functions str.upper() and str.lower() will return a string with all the letters of an original string converted to upper- or lower-case letters. Because strings are immutable data types, the returned string will be a new string. Any characters in the string that are not letters will not be changed.

'Hello World!'

3.5 Find/Replace (also a String Method)

'hello world!'
# Find first occcurance of o
# Replaces all occurances
'hellO wOrld!'

3.6 Practice

story = """There once lived in a town of Persia two brothers, one named Cassim and the other Ali Baba. Their father divided a small inheritance equally between them. Cassim married a very rich wife, and became a wealthy merchant. Ali Baba married a woman as poor as himself, and lived by cutting wood, and bringing it upon three asses into the town to sell."""
'There once lived in a town of Persia two brothers, one named Cassim and the other Ali Baba. Their father divided a small inheritance equally between them. Cassim married a very rich wife, and became a wealthy merchant. Ali Baba married a woman as poor as himself, and lived by cutting wood, and bringing it upon three asses into the town to sell.'

What is the Result of




What is output of


What is the output of this


How do you find out the length of story?

How do you add “ Really?” to the end of the story?

How do replace “Ali Baba” with “John Doe” and “the town” with “Singapore” in one line?

alt text

4. Numbers

In Python, like in all programming languages, data types are used to classify one particular type of data. This is important because the specific data type you use will determine what values you can assign to it and what you can do to it (including what operations you can perform on it).

4.1 Basics

One way to think about data types is to consider the different types of data that we use in the real world. An example of data in the real world are numbers: we may use whole numbers (0, 1, 2, …), integers (…, -1, 0, 1, …), and irrational numbers (π), for example.

Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …). An integer can also be known as an int. As with other programming languages, you should not use commas in numbers of four digits or more, so when you write 1,000 in your program, write it as 1000.

# Addition
number = 2 + 2
# Same result as above (Shortcut)
number = 2
number += 2
# Difference?
# For computers, each data type can be thought of as being quite different, like words and numbers, 
# so we will have to be careful about how we use them to assign values and how we manipulate them through operations.

number = '2' + '2'

4.2 Floats

Any number you enter in Python will be interpreted as a number; you are not required to declare what kind of data type you are entering. Python will consider any number written without decimals as an integer (as in 138) and any number written with decimals as a float (as in 138.0).

A floating-point number or a float is a real number, meaning that it can be either a rational or an irrational number. Because of this, floating-point numbers can be numbers that can contain a fractional part, such as 9.0 or -116.42. Simply speaking, for the purposes of thinking of a float in a Python program, it is a number that contains a decimal point.

x = 4

4.3 Int/Float Methods


4.4 Libraries


Shorter List

# You can import modules
import math
# You can get specific functions from a module
from math import ceil, floor
# You can import all functions from a module.
# Warning: this is not recommended
from math import *

# You can shorten module names
import math as m
# Now as a shortcut

4.6 Practice

Result of the following?

type(1 + 32)

Result of the following?

x = 4

X += 6

Difference between

width = 20








x = 'hello'
x = 'hello' + ' world'


x = 5
x + 6
x / 1

alt text

5. Lists

A list is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ]

5.1 Creation

Lists are a very flexible data type because they are mutable in that they can have values added, removed, and changed. There is a data type that is similar to lists but that can’t be changed, and that is called a tuple.

sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp']
['shark', 'cuttlefish', 'squid', 'mantis shrimp']
# Appending
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab']
# Can be any type
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab', 1000]
# Can be any type even another list
list_example = ['dog', 'cat']
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab', 1000, ['dog', 'cat']]

5.2 Indexing

['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab', 1000, ['dog', 'cat']]
# : still works as expected!
['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab', 1000]

5.3 List Methods

Already covered this above


list.insert(position, item)

sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab']
['anchovy', 'shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab']


more_fish = ['goby','herring','ide','kissing gourami']
['anchovy', 'shark', 'cuttlefish', 'squid', 'mantis shrimp', 'crab', 'goby', 'herring', 'ide', 'kissing gourami']

5.4 Practice

Output of

list_ = []

Output of

shopping = ['milk', 'tea', 'coke']


alt text

6. Booleans

The Boolean data type can be one of two values, either True or False. We use Booleans in programming to make comparisons and to control the flow of the program.

Booleans represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science. Named for the mathematician George Boole, the word Boolean always begins with a capitalized B. The values True and False will also always be with a capital T and F respectively, as they are special values in Python.

Comparison Operators

Operator What it means
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

6.1 Basics

x = True
 5 == 7
for i in range(0, 5):
5 != 7
'John' == 'john'

6.2 Logical Operators

There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False. These operators are and, or, and not and are defined in the table below.

Logical operators are typically used to evaluate whether two or more expressions are true or not true. For example, they can be used to determine if the grade is passing and that the student is registered in the course, and if both cases are true then the student will be assigned a grade in the system.

Operator What it means What it looks like
and True if both are true x and y
or True if at least one is true x or y
not True only if false not x
4 == 4 and 4 > 2
4 == 4 and 4 > 6
4 == 4 or 4 > 6

6.3 List Comparisons

list_example = [2, 'hi']

2 in list_example
'hi' in list_example

6.4 Practice

Result of

x = 4

x > 4

Result of

x => 4

alt text

7 Loops

Using loops in computer programming allows us to automate and repeat similar tasks multiple times.

A for loop implements the repeated execution of code based on a loop counter or loop variable. This means that for loops are used most often when the number of iterations is known before entering the loop, unlike while loops which are conditionally based.

In Python, for loops are constructed like so:

for [iterating variable] in [sequence]:
    [do something]

The something that is being done will be executed until the sequence is over.

This for loop sets up i as its iterating variable, and the sequence exists in the range of 0 to 5.

Then within the loop we print out one integer per loop iteration. Keep in mind that in programming we tend to begin at index 0, so that is why although 5 numbers are printed out, they range from 0-4.

You’ll commonly see and use for loops when a program needs to repeat a block of code a number of times.

For Loops using range()

Range(start=0, stop, step=1)

When working with range(), you can pass between 1 and 3 integer arguments to it:

  • start states the integer value at which the sequence begins, if this is not included then start begins at 0
  • stop is always required and is the integer that is counted up to but not included
  • step sets how much to increase (or decrease in the case of negative numbers) the next iteration, if this is omitted then step defaults to 1

7.1 For Loops using Sequential Data Types

Lists and other data sequence types can also be leveraged as iteration parameters in for loops. Rather than iterating through a range(), you can define a list and iterate through that list.

We’ll assign a list to a variable, and then iterate through the list:

sharks = [‘hammerhead’, ‘great white’, ‘dogfish’, ‘bullhead’]

for shark in sharks: print(shark) In this case, we are printing out each item in the list. Though we used the variable shark, we could have called the variable any other valid variable name and we would get the same output:

sharks = ['hammerhead', 'great white', 'dogfish', 'bullhead']
for shark in sharks:
great white
# More useful application
shoppinglist = ['broom', 'mop', 'towel']
shoppinglist_prices = [0.4, 1, 0.2]

total = 0

# Loop thru the shoppinglist
for i in range(0, len(shoppinglist)):
    print(shoppinglist[i] + ' costs ' + str(shoppinglist_prices[i]))
    total += shoppinglist_prices[i]
    # The same result as 
    #total = total + shoppinglist_prices[i]

print('Total Price = ' + str(total))
broom costs 0.4
mop costs 1
towel costs 0.2
Total Price = 1.5999999999999999

7.2 Nested For Loops

Loops can be nested in Python, as they can with other programming languages.

A nested loop is a loop that occurs within another loop, structurally similar to nested if statements. These are constructed like so:

for [first iterating variable] in [outer loop]: # Outer loop

    [do something]  # Optional
    for [second iterating variable] in [nested loop]:   # Nested loop
        [do something]  

The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns back to the top of the outer loop, completing the second iteration and again triggering the nested loop. Again, the nested loop runs to completion, and the program returns back to the top of the outer loop until the sequence is complete or a break or other statement disrupts the process.

num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']

for number in num_list:
    for letter in alpha_list:

7.3 Practice

What is the result of total?

sample = [1,2,3]

total = 0
for i in sample:
    total = total + i -1

What is the result of?

list_of_lists = [ [3, 5, 1], [7, 3, 1]]
for lists in list_of_lists:
    for x in lists[:-1]:
        print (x)

alt text

8 Conditional Statements

Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

When we fully execute each statement of a program, moving from the top to the bottom with each line executed in order, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.

Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.

We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

8.1 If Else

grade = 64

if grade >= 65:                 # Condition
    print("Passing grade")      # Clause

    print("Failing grade")
Failing grade
grade = 82

if grade >= 90:                 # Condition
    print("A Grade")            # Clause

elif grade >= 80 and grade <90:
    print("B Grade")
    print("Some Other Grade")
B Grade

Comparison Operators

Operator What it means
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

8.2 Nestled Ifs

Once you are feeling comfortable with the if, elif, and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:

if statement1:              #outer if statement

    if nested_statement:    #nested if statement

    else                    #nested else statement

else:                       #outer else statement

8.3 Practice

What is the result of the following?

shoppinglist = ['soap', 'meat']

for item in shoppinglist:
    if item == 'meat':
        print('Please pay 10.50')
    elif item == 'towel':
        print('Please pay 3')
        print('Unknown Cost')

What is the result of the following?

grade = 64
name = 'tom'

if grade >= 65:                 
    print("Passing grade") 
    if name == 'tom':
        print("Passing grade")
        print("Failing grade")
    print("Failing grade")

alt text

9 Dictionaries

The dictionary is Python’s built-in mapping type. This means that dictionaries map keys to values and these key-value pairs are a useful way to store data in Python. A dictionary is constructed with curly braces on either side { }.

Typically used to hold data that are related, such as the information contained in an ID, a dictionary looks like this:

9.1 Basics

# Creating a dictionary
shoppinglist = ['soap', 'milk']
shoppingdict = {'soap': 3, 'milk': 1.5}
{'milk': 1.5, 'soap': 3}
# Selecting
# Adding to the dictionary
shoppingdict['juice'] = 4
{'juice': 4, 'milk': 1.5, 'soap': 3}

9.2 Looping Through a Dictionary

total = 0
for key, value in shoppingdict.items():
    total += value

9.3 Practice

Display the value for the key ‘milk’

shoppingcart = {'soap': 'Y', 'milk': 'N'}

Complete the following by summing only items in the shoppingcart?

shoppingdict = {'soap': 3, 'milk': 1.5}
shoppingcart = {'soap': 'Y', 'milk': 'N'}

for key, value in shoppingdict.items():
        total += value

alt text

10 Your Own Functions

Let’s start with turning the classic “Hello, World!” program into a function.

We’ll create a new text file in our text editor of choice, and call the program Then, we’ll define the function.

A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon.

10.1 Basics

In this case, we’ll define a function named hello():

def hello():
    print("Hello, World!")

Our function is now fully defined, but if we run the program at this point, nothing will happen since we didn’t call the function.

So, outside of our defined function block, let’s call the function with hello():

def hello():
    print("Hello, World!")


Hello, World!

You can pass a parameter value into a function, and a function can also produce a value.

A function can produce a value with the return statement, which will exit a function and optionally pass an expression back to the caller. If you use a return statement with no arguments, the function will return None.

def calculate_downpayment():
    return 1000000 * 0.2



10.2 Parameters

So far we have looked at functions with empty parentheses that do not take arguments, but we can define parameters in function definitions within their parentheses.

A parameter is a named entity in a function definition, specifying an argument that the function can accept.

def calculate_downpayment(house_price):
    return house_price * 0.2

# Default value
def calculate_downpayment(house_price=1000000):
    return house_price * 0.2

# Multiple Parameters
def calculate_downpayment(house_price=1000000, rate=0.2):
    return house_price * rate

# For second paramter must include name

10.3 Function Returns

The Return statement can be more complex than just returning a single value

# Return a dictionary
def calculate_downpayment(house_price=1000000, rate=0.2):
    return { 'downpayment' : house_price * rate, 'loan': house_price * (1-rate)}

{'downpayment': 200000.0, 'loan': 800000.0}
x = calculate_downpayment()

10.4 Practice

Create a Function that can debit and credit a bank account

def account(starting, debit=0, credit=0):

    # Add Code here

    return ending value

Edit the function such that if you have >0 properties then your rate is 0.3 instead of 0.2

def calculate_downpayment(house_price=1000000, properties=0):

    # If else....

    return house_price * rate

alt text

11 Classes

Python is an object-oriented programming language. Object-oriented programming (OOP) focuses on creating reusable patterns of code, in contrast to procedural programming, which focuses on explicit sequenced instructions. When working on complex programs in particular, object-oriented programming lets you reuse code and write code that is more readable, which in turn makes it more maintainable.

One of the most important concepts in object-oriented programming is the distinction between classes and objects, which are defined as follows:

Class — A blueprint created by a programmer for an object. This defines a set of attributes that will characterize any object that is instantiated from this class.

Object — An instance of a class. This is the realized version of the class, where the class is manifested in the program.

These are used to create patterns (in the case of classes) and then make use of the patterns (in the case of objects).

11.1 Classes

Classes are like a blueprint or a prototype that you can define to use to create objects.

We define classes by using the class keyword, similar to how we define functions by using the def keyword.

Let’s define a class called Shark that has two functions associated with it, one for swimming and one for being awesome:

class Shark:
    def swim(self):
        print("The shark is swimming.")

    def be_awesome(self):
        print("The shark is being awesome.")

11.2 Objects

An object is an instance of a class. We can take the Shark class defined above, and use it to create an object or instance of it.

We’ll make a Shark object called sammy:

sammy = Shark()
The shark is swimming.
The shark is being awesome.

Lets convert the previous example into a class

class SGLoanCalculator:
    def calculate_downpayment(self, house_price):
        return house_price * 0.2

    def calculate_grant(self, type_house):
        if type_house == 'ec':
            return 30000
            return 0
# Create object calculation1
calculation1 = SGLoanCalculator()
# Another object
calculation2 = SGLoanCalculator()

11.3 The Constructor Method

The constructor method is used to initialize data. It is run as soon as an object of a class is instantiated. Also known as the init method, it will be the first definition of a class and looks like this:

class SGLoanCalculator:
    def __init__(self, house_price, type_house):
        self.house_price = house_price
        self.type_house = type_house
    def calculate_downpayment(self):
        return self.house_price * 0.2

    def calculate_grant(self):
        if self.type_house == 'ec':
            return 30000
            return 0

Because the constructor method is automatically initialized, we do not need to explicitly call it, only pass the arguments in the parentheses following the class name when we create a new instance of the class.

person1 = SGLoanCalculator(800000, 'ec')

Making it more useful

class SGLoanCalculator:
    def __init__(self, house_price, type_house):
        self.house_price = house_price
        self.type_house = type_house
    def calculate_downpayment(self):
        return self.house_price * 0.2

    def calculate_grant(self):
        if self.type_house == 'ec':
            return 30000
            return 0

    def final_calculation(self):
        final_downpayment = self.calculate_downpayment() - self.calculate_grant()
        print('Your final downpayment is ' +str(final_downpayment))
person1 = SGLoanCalculator(800000, 'ec')
Your final downpayment is 130000.0

11.4 Practice

Can you understand how this works?

class PropertyCalculator():

    def __init__(self, property_value=1000000, loan_value=800000):
        self.property_value = property_value
        self.loan_value = loan_value

    def calculate_initial(self):
        Calculate Initial Payment
        cash = 0.05
        cpf = 0.15

        property_min_cash = cash * self.property_value
        property_cpf = cpf * self.property_value

        agent_fee = 0
        legal_fee = 0.003 * self.property_value
        stamp_duty = 0.0246 * self.property_value
        valuation_fee = 500
        total_fees = agent_fee + legal_fee + stamp_duty + valuation_fee
        return {'cpf': property_cpf, 'cash': property_min_cash, 'total': total_fees}
person1 = PropertyCalculator()
{'cash': 50000.0, 'cpf': 150000.0, 'total': 28100.0}

Can you recreate the Account (Debit/Credit) function previously as a Class?

alt text

12 Starting A Flask Project


# create an empty directory for our project
mkdir lambda-hello-world
cd lambda-hello-world
# Init the Pipfile and a virtual environment for the project.
pipenv --three
# activate the virtual environment
pipenv shell
# install Zappa and Flask along with the AWS command line tools
pipenv install zappa flask
pipenv install --dev awscli
# optionally install some handy development tools inside the virtual environment
pipenv install --dev flake8 autopep8 ipython

Project Management (pipenv)

$ pipenv
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

  --where          Output project home information.
  --venv           Output virtualenv information.
  --rm             Remove the virtualenv.
  --bare           Minimal output.
  --three / --two  Use Python 3/2 when creating virtualenv.
  --python TEXT    Specify which version of Python virtualenv should use.
  -h, --help       Show this message then exit.
  --version        Show the version and exit.

Usage Examples:
   Create a new project using Python 3:
   $ pipenv --three

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile:
   $ pipenv lock

  check      Checks PEP 508 markers provided in Pipfile.
  install    Installs provided packages and adds them to...
  lock       Generates Pipfile.lock.
  run        Spawns a command installed into the...
  shell      Spawns a shell within the virtualenv.
  uninstall  Un-installs a provided package and removes it...
  update     Updates pip to latest version, uninstalls all...

from flask import Flask
app = Flask(__name__)
def index():
    return "Hello, world!", 200
# We only need this for local development.
if __name__ == '__main__':


# Set Enivroment Variable

# Run Flask app
flask run

comments powered by Disqus