Branching & Iteration
HSS 611: Programming for HSS
Sep 4, 2025
Agenda
Why Python?
Objects and types
String datatype
Comparison operators
Iteration and loops: for
and while
Indentation
Control flow: if
, elif
, else
We’ll begin with a short discussion of why Python has become one of the most widely used programming languages
Next, we’ll look at Objects and data types. In Python, everything is an object, and understanding data types helps us know what we can and can’t do with those objects.
After that, we’ll get into the String datatype. Strings are about how Python handles text, and since text is very common in programming, this will be especially useful.
Then we’ll cover Comparison operators. These let us check whether things are equal, greater, or less, and they’re the foundation for making decisions in our code.
Following that, we’ll move on to Iteration and loops, focusing on for and while. Loops let us repeat tasks without writing the same line of code over and over again.
We’ll also talk about Indentation. Unlike many other languages, Python uses indentation as part of its syntax, so paying attention to spacing is critical.
Finally, we’ll finish with Control flow: if, elif, and else. These statements allow our programs to make choices and follow different paths of the code block depending on certain conditions.
Python
Why Python?
A general-purpose programming language
First released in 1991
Used in web development, game development, data science, academic research, etc.
Booming in machine learning & artificial intelligence
Python
Why Python?
Open source & free
English-like, readable syntax
Very popular across domains
Used in web development, game development, data science, academic research, etc.
Booming in machine learning & artificial intelligence
Python
Python for HSS
Data cleaning and manipulation
Handling vectors and matrices
Web data collection
Visualization
Text-as-data/NLP/LLM, machine/deep learning
Network analysis
Statistical analysis (to a lesser degree)
Python
Programming environments
Install Python (https://www.python.org/)
Or use tools like Anaconda
Automatically installs Python and widely-used libraries
Makes Python library/package management easy
A wide selection of environments: VS Code, Jupyter Notebook, etc.
Google Colab
Browser-based (no need to install), and sharable with a link
Free (or subscribed) access to computing resources (CPU/RAM/GPU)
You can start by installing Python directly from the official website, or use tools like Anaconda, which not only installs Python itself but also includes many widely used libraries and makes package management easier.
There’s a wide selection of environments you can work in, such as VS Code or Jupyter Notebook, depending on your preferences
Another great option is Google Colab: it runs in the browser, requires no installation, and you can share work with just a link. It also provides free—or, with a subscription, more powerful—computing resources like CPU, RAM, and even GPUs.
Data types
Python creates and manipulates data objects
Objects have a type, which defines how they can be used
Two (broad) object types
Scalar (cannot be subdivided)
Non-scalar (e.g., list, tuple, dictionary, set)
Everything in Python is an object, and every object has a type, which determines what you can do with it.
Broadly speaking, there are two categories of objects.
Some are scalar—these can’t be broken down further, like numbers.
Others are non-scalar—things like lists, tuples, dictionaries, or sets, which we will discuss soon. These can hold multiple pieces of data and be subdivided or organized in different ways.
Data types
Scalar Objects
int
- integers, e.g. 3
or -142
float
- real numbers, e.g. 4.2
or -3.5
bool
- Boolean, also known as logical in some languages, True
or False
NoneType
- a special type indicating “missing” with one possible value, None
Among scalar objects, first, we have integers, indicated as “int.” These are whole numbers without any decimal points, like 3 or -142. Of course we use these when we need to work with counts, indices, or other discrete quantities.
Next, we have floating-point numbers, or “float.” Floats are real numbers that can have a fractional component, like 4.2 or -3.5. You use them when you need more precision, such as in measurements or mathematical calculations.
Then, there’s the Boolean type, or “bool”. Booleans are used to represent truth values, True or False. They are critical for making decisions in your code, such as in if statements and loops, which will be discussed at the end of the lecture today.
Finally, we have NoneType. It represents the absence of a value or a “missing” value. This type has a single value: None (it’s often used as a placeholder or default return type for functions that don’t explicitly return a value).
These scalar types are the foundation (or building blocks) of data representation in Python and are essential for working with variables and performing operations in your code.
Data types
Is str
scalar or not?
String (str
): a sequences of characters
Typically used to represent text
Whether str
is scalar or not depends on the context
Please enable JavaScript to experience the dynamic code cell content on this page.
Data types
Type conversions (casting)
Objects of different types can be converted to one another
Please enable JavaScript to experience the dynamic code cell content on this page.
Please enable JavaScript to experience the dynamic code cell content on this page.
string
data type
Concatenate with +
Please enable JavaScript to experience the dynamic code cell content on this page.
string
data type
To create a string with double quotes in it
Create it with single quotes
And vice versa
Please enable JavaScript to experience the dynamic code cell content on this page.
string
data type
If you need both, '''
can be used
Please enable JavaScript to experience the dynamic code cell content on this page.
Variables and values
Equal sign (=) is used for assignment of a value to a variable
A variable is a name that refers to a value stored in memory (a label attached to an object)
Easier to read and debug
Please enable JavaScript to experience the dynamic code cell content on this page.
Variables and values
Retrieve value by invoking the name of the variable
Please enable JavaScript to experience the dynamic code cell content on this page.
Please enable JavaScript to experience the dynamic code cell content on this page.
Variables and values
Rebinding
One can rebind a variable name to a different value
Please enable JavaScript to experience the dynamic code cell content on this page.
Variables and values
If a value changes, it changes in just one place
Please enable JavaScript to experience the dynamic code cell content on this page.
Please enable JavaScript to experience the dynamic code cell content on this page.
Please enable JavaScript to experience the dynamic code cell content on this page.
Comparison operators
Used to compare to variables to one another
Note the signs <
or >
precede =
These evaluate to a Boolean
var1 > var2
var1 >= var2
var1 != var2
Please enable JavaScript to experience the dynamic code cell content on this page.
Comparison operators
This is widely useful, including
Control flow
And many many more
Control flow: branching
if
is used to evaluate if a condition is True
if <condition>:
<this is ran if condition is True>
<this is ran if condition is True>
Control flow: branching
Indentation
Be careful and meticulous when you indent multiple times (and multiple levels)
The expressions should (by convention) be indented by 4 spaces or a tab (that’s how Python understands that those are the expressions to be run if the condition is True)
if <condition>:
<this is ran if condition is True>
<this is ran if condition is True>
<this does not depend on condition>
Control flow: branching
Best practices for indentation
Either always use tabs or always spaces
Python community mostly uses 4 spaces
Many environments will allow you to automatically convert tabs to 4 spaces
Applicable not only to branching but also to: for
, while
, with
, def
, class
, try
, except
, etc.
For more discussion see here .
Control flow: branching
We can also use else
with if
Run a
if condition is True, otherwise run b
if <condition>:
<a>
else:
<b>
Control flow: branching
Example
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: branching
elif
stands for ‘else if’
If condition1 is True, run a
If condition1 is False but condition2 is True, run b
if <condition1>:
<a>
elif <condition2>:
<b>
elif <condition3>:
<c>
.
.
else:
<z>
Control flow: branching
Note that, in this setting, last code is only run only if everything above is False
E.g. c
will not be run if condition1 and condition2 are not both False
if <condition1>:
<a>
elif <condition2>:
<b>
elif <condition3>:
<c>
.
.
else:
<z>
Control flow: branching
Example
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Run codes as long as a condition is True
while <condition>:
<a>
<b>
...
Control flow: while loops
Example
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Another example
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Note that x = x + 1
can be shortened to x += 1
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Useful when the number of iterations is known
Every time through the loop, <variable>
takes a new value (iterating through <iterable>
)
for <variable> in <iterable>:
<a>
<b>
...
Control flow: while loops
Iterable is oftentimes range(<some_num>)
Can also be a list, tuple, string, dictionary, Pandas Series, etc.
for <variable> in range(<some_num>):
<expression>
<expression>
Control flow: while loops
range(start, stop, step)
By default, start = 0
and step = 1
Only stop
is required
It will start at 0, loop until stop - 1
Control flow: while loops
range(start, stop, step)
If we supply one argument, it’s understood as the stop
argument
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
range(start, stop, step)
Starts at 11 and ends before 15
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
range(start, stop, step)
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Can iterate over many other things
Please enable JavaScript to experience the dynamic code cell content on this page.
Control flow: while loops
Can iterate over many other things
Please enable JavaScript to experience the dynamic code cell content on this page.
break
and continue
statements
break
exits the loop entirely
The remaining expressions are not evaluated
Please enable JavaScript to experience the dynamic code cell content on this page.
break
and continue
statements
continue
only skips the current iteration
“Continue”s with the remaining iterations
Please enable JavaScript to experience the dynamic code cell content on this page.
The continue statement is useful in data analysis when you want to skip certain iterations of a loop based on a condition without stopping the entire loop.
This allows you to efficiently handle exceptions, missing data, or specific cases that don’t need processing.
Skipping Missing or Invalid Data: When iterating over a dataset, you might encounter missing or invalid values. Using continue allows you to skip those entries and process only the valid ones without breaking the loop.
Filtering Unwanted Data: In scenarios where certain data points don’t meet specific criteria, you can use continue to skip processing them and focus on the relevant data. For instance, ignoring data points that fall outside a desired range.
break
and continue
statements
break
and continue
can be used in both for and while loops
Please enable JavaScript to experience the dynamic code cell content on this page.