Branching & Iteration

HSS 611: Programming for HSS

Taegyoon Kim

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

Python

Why Python?

  • A general-purpose programming language
  • First released in 1991

Python

Why Python?

  • Open source & free
  • English-like, readable syntax
  • Very popular across domains

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)

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)

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

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

Data types

Type conversions (casting)

  • Objects of different types can be converted to one another
  • Be careful, though

string data type

Texts, letters, characters, spaces, digits, etc.

  • Created with single or double quotes

string data type

Concatenate with +

string data type

Strings can also be created with ''' or """

  • Useful to handle multi-line strings as well

string data type

To create a string with double quotes in it

  • Create it with single quotes
  • And vice versa

string data type

If you need both, ''' can be used

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

Variables and values

Retrieve value by invoking the name of the variable

Variables and values

Rebinding

  • One can rebind a variable name to a different value

Variables and values

If a value changes, it changes in just one place

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

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

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

Control flow: branching

Further note on indentation

  • Many nested indentations are normal and common
  • Note how indentation determines which else belongs to which if
  • What will this return?

Control flow: branching

Further note on indentation

  • How about this?

Control flow: while loops

Run codes as long as a condition is True

while <condition>:
    <a>
    <b>
    ...

Control flow: while loops

Example

Control flow: while loops

Another example

Control flow: while loops

Note that x = x + 1 can be shortened to x += 1

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

Control flow: while loops

range(start, stop, step)

  • Starts at 11 and ends before 15

Control flow: while loops

range(start, stop, step)

  • What will this return?

Control flow: while loops

Can iterate over many other things

Control flow: while loops

Can iterate over many other things

break and continue statements

break exits the loop entirely

  • The remaining expressions are not evaluated

break and continue statements

continue only skips the current iteration

  • “Continue”s with the remaining iterations

break and continue statements

In nested loops, break exits only the innermost loop

break and continue statements

Similarly, continue skips the current iteration in the innermost loop

break and continue statements

break and continue can be used in both for and while loops