Data Analyst Program

Python · Week 2 of 4 · 5–6 hours

Data Structures, Conditional Statements and Loops

Store collections of data and process them automatically.

Learning objectives

By the end of this week you will be able to:

  • Create and use lists, tuples, dictionaries and sets.
  • Write if, elif and else statements.
  • Repeat work with for and while loops.
  • Combine loops and conditions to summarize data.

Lessons

Data Structures

Real data comes in groups, so Python has containers to hold many values.

List: an ordered collection you can change. Square brackets.

sales = [120, 95, 210, 180]
sales[0]        # 120 (counting starts at 0)
sales[-1]       # 180 (last item)
sales.append(150)
len(sales)      # 5
sum(sales), max(sales)

Tuple: like a list but cannot be changed. Round brackets: point = (3, 5). Use for values that belong together and should not change.

Dictionary: stores key: value pairs, like a mini lookup table. Curly brackets.

prices = {"apple": 0.5, "bread": 2.25, "milk": 1.8}
prices["bread"]          # 2.25
prices["eggs"] = 3.1     # add a new pair
prices.keys(), prices.values()

Set: unordered, unique values only. set(["North","South","North"]) gives {"North","South"}. Great for finding distinct values.

When to use which: a list for a sequence of values, a dictionary when you look things up by name, a set when you only care about unique values.

Conditional Statements

Conditions let your program choose what to do. Python uses indentation (four spaces) to show which lines belong to each branch.

order_total = 75
if order_total >= 100:
    shipping = 0
elif order_total >= 50:
    shipping = 5
else:
    shipping = 10

Python checks each test from top to bottom and runs the first one that is True. Comparison operators: == (equal; note the double sign), !=, >, <, >=, <=. Combine tests with and, or, not. Check membership with in: if region in ["North", "South"]:

Common error: forgetting the colon at the end of the if line, or not indenting the next line.

Loops

A for loop repeats code once for each item in a collection:

sales = [120, 95, 210, 180]
total = 0
for amount in sales:
    total = total + amount
print(total)   # 605

range(5) produces 0, 1, 2, 3, 4, useful when you need to repeat something a set number of times. Loop over a dictionary with for item, price in prices.items():

A while loop repeats as long as a condition is True. Make sure something inside the loop eventually makes the condition False, or it will run forever.

balance = 1000
years = 0
while balance < 2000:
    balance = balance * 1.07
    years += 1

Loops plus conditions are how you summarize data by hand: count how many orders were over 100, or build a dictionary of totals per region. Next week pandas will do this in one line, but understanding the loop shows you what pandas is doing behind the scenes.

Watch

Practice

orders = [("North", 120), ("South", 95), ("North", 210), ("East", 180), ("South", 60)]
  1. Loop through the orders and print each region and amount.
  2. Count how many orders are over 100.
  3. Build a dictionary with the total amount for each region.
  4. Print the set of unique regions.
  5. Label each order Small, Medium (100 to 199) or Large (200+) using if/elif/else.

Check your understanding

Try each question first, then open it to see the answer.

What is the first item in a list called nums?

nums[0].

Which structure would you use to look up a product's price by its name?

A dictionary.

What is the difference between = and ==?

= assigns a value; == compares two values.

Assignment

Submit your notebook with the five practice tasks solved and a short note on which part was hardest and why.