Python Bootcamp
Day 1: Control Flow
Introduction
Introduction: Ice Breaker
1. What is your name?
2. What subject do you teach?
3. What programming, if any, have you done?
4. What what do you want to learn in this
bootcamp?
Introduction: Whoami?
Bootcamp
Bootcamp: Website
All of the course information can be found at:
http://yld.me/pbc-su19
Bootcamp: Topics
Programming Basics Special Topics
● Control Flow ● Visualizing Data
● Data Structures ● Filtering Data
● Image Processing
● Machine Learning
What is a Computer?
A Computer is...
A general purpose information processing
machine.
A digital computer is an electronic device that processes
binary data.
Logical Construction
What is Programming?
Program
● Concrete statement of steps that a real
computer must perform to accomplish a
task.
● One or more algorithms expressed in a
form that a computer can process directly.
A sequence instructions that a computer
can interpret and execute.
Programming
● Act of encoding the steps a computer must
perform to accomplish a task.
● The most important skill required for
programming is problem-solving.
○ What are the steps required to solve problem?*
○ What is the best way to encode the steps to the
computer?
Activity: Design Max Height Algorithm
Design an algorithm for determining the
maximum height of the people in the class.
● How would you do this without a computer?
● What information must be stored or recorded?
● What is the sequence of steps required to solve this
problem?
What is Python?
Python
Python is an interpreted, object-oriented,
high-level programming language with
dynamic semantics.
Interpreter vs Compiler
The computer only understands machine language,
therefore we need a way to translate our high-level code
into the low-level machine code.
1. Interpretation
A program reads, parses,
and translates our source
code on-the-fly for execution
2. Compilation
A program processes our source code all at once and
produces an executable
Why Python?
1. Encourages very readable and well
structured code
2. Rich ecosystem of libraries and
frameworks (NumPy, SciPy, Pandas,
NLTK, Django, Flask, Requests, Keras, etc.)
3. Free and open source, widely spread, with
vibrant community
Who Uses Python?
Activity: Install Anaconda
For this bootcamp, we will be using the Python
3.7 flavor of the Anaconda distribution:
https://www.anaconda.com/distribution/
Download and install this
software development kit.
Python Basics
Control Flow
Activity: Code Max Height Algorithm
Once Anaconda is installed, launch the Jupyter
Notebook.
This will open a webpage in your web browser
that will allow you to type in Python code and
execute it.
We will now translate our max height
algorithm into functional Python code
together!
Activity: Fizz Buzz
Write a program that prints the numbers from 1 to 100. But
for multiples of three print "Fizz" instead of the number and
for the multiples of five print "Buzz". For numbers which
are multiples of both three and five print "FizzBuzz".
Expressions
Expressions: Values
Every object in Python has a value. Likewise,
every value belongs to a certain type which
determines the behavior and properties of that
object.
>>> type(5)
int
Expressions: Evaluation
An expression is a combination of values,
variables, and operators.
x + 1
● An operator is a symbol that represents a
kind of computation.
● Every expression has a value when
evaluated.
Expressions: Arithmetic
Operator Description
x + y Adds x and y
x - y Subtracts y from x
x * y Multiplies x by y
x ** y x to the y Power
x / y Divides x by y (float)
x // y Divides x by y (int)
x % y Divides x by y (remainder)
Evaluate from left-to-right, following
PEMDAS.
Expressions: Boolean
Python has the notion of boolean values: True
and False. We can form boolean expressions
using the and, or, and not operators:
>>> True and False
False
>>> True or False
True
>>> not True
False
Expressions: Comparisons
To create boolean expressions, we can use
logical comparisons:
Operator Description
x == y True if x is equal to y, otherwise False
x != y True if x is not equal to y, otherwise False
x < y True if x is less than y, otherwise False
x <= y True if x is less than or equal to y, otherwise False
x > y True if x is greater than y, otherwise False
x >= y True if x is greater than or equal to y, otherwise False
Variables
Variables: Assignment
A variable is a name for a location in memory
that holds a value:
x = 13 # Set x to 13
print(x + 5) # Print 13 + 5
● To set this value, we use the assignment statement
whereby the expression on the right is evaluated and
then stored in the variable on the left
● To use this value in an expression, we simply use the
variable name
Python Tutor
Variables: Tracing
# Code x Description
1. x = 1 1 Set x to 1
2. x + 1 1 No update
3. x = x + 1 2 Set x to 1 + 1
4. x - 1 2 No update
5. x = x * x 4 Set x to 2 * 2
We only update a variable if there is an
assignment operation.
Functions
Functions: Use
A function is a named sequence of
statements that performs a computation.
>>> int('10', 2)
2
● To execute a function, we call it by name and pass it
an appropriate set of input arguments.
● The output or result of a function is called the return
value.
Functions: Definition
A function definition specifies the name of a
new function, the list of input arguments, and
the sequence of statements to execute when
the function is called.
def function_name(argument): # Header
''' Docstring '''
statement(s) # Body
return result
Functions: Execution
● Programs are always executed
sequentially, one statement at at time.
● Function definitions create new functions,
but do not execute the bodies or
statements within the functions until they
are called.
● When we call a function, we jump to the
function being called, execute the callee’s
body of statements, and then return to the
Functions: Return Values
To output a result, a function uses the return
statement to pass results back to the caller.
def double(x): vs def twice(x):
return x + x print(x + x)
>>> x = double(2) >>> x = twice(2)
>>> x >>> x
4 None
Functions: Scope
● Inside a function, the arguments are
assigned to local variables called
parameters.
● The name of the parameter inside the
function is separated or isolated from the
name outside the function. This separation of
namespaces is called scoping.
Conditional Execution
Conditional Statements
We use conditional statements to check
boolean expressions (which we call
conditions), and change the behavior of the
program accordingly.
if condition: if n == 0:
statement(s) print('n is zero')
Alternative Execution
Alternative execution is when we have two
possibilities and the condition determines
which one gets executed.
if condition:
statement(s) # Condition is True
else:
statement(s) # Condition is False
Chained Conditionals
When we want to if condition 1:
statements(s)
check more than one
elif condition 2:
condition, we can use statements(s)
chained conditionals. elif condition 3:
Each condition is statements(s)
else:
checked in the order statements(s)
that they appear; if one
is triggered, then the
rest are skipped.
Nested Conditionals
Conditional statements can be nested or
placed inside another conditional statement.
Example
if a > b:
if a < c:
print('a is between b and c')
Repeated Execution
While: Overview
We can use a while statement to repeatedly
execute a series of tasks (i.e. a loop).
Syntax Example
while condition: n = 0
statement(s) while n < 10:
print(n)
n = n + 1
While: Control Flow
1. Evaluate condition (which is a boolean
expression).
2. If condition is False, then exit loop and
continue program.
3. If condition is True, then execute statements
in body and then go to step 1.
While: Notes
● Each time through the body of a loop is
called an iteration.
● The condition normally contains a variable
that changes within the body of the loop so
that we can eventually exit the loop.
● If a loop never exits, then this is called an
infinite loop.
For: Overview
Iterating through a definite set of objects is a
common looping pattern, so Python provides
the for statement.
Syntax Example
for item in dataset: for i in [0, 1, 2, 3]:
statement(s) print(i)
For: Control Flow
1. Extract one element from the dataset.
2. Execute the body of for loop with item bound
to the element.
3. Go to step 1.
For: Range
We can generate a list of numbers using the
range function:
>>> range(0, 3)
[0, 1, 2]
>>> for i in range(0, 3):
print(i)
0
1
2
For: Enumerate
We can generate a list of pairs consisting of
the index and the item using enumerate:
>>> list(enumerate(['a', 'b', 'c']))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> for index, letter in enumerate('abc'):
print(index, letter)
0 a
1 b
2 c
Break
We can exit a loop immediately by using the
break statement
import random
while True:
r = random.randint(0, 10)
if r == 0:
break
print(r)
print(r)
Continue
We can skip the rest of the loop body and
move on to the next iteration by using
continue
while True:
r = random.randint(0, 10)
if r == 0:
break
if r % 2:
continue
print('{0} is even'.format(r))