ECON 290 · Economic Data and Computing

A First Look at Programming for Data Analysis

Meet variables, lists, loops, functions and tables in Python, using small economic examples you can follow line by line.

Key takeaways

  • A program is a precise recipe; the computer follows it exactly, which makes the work repeatable and checkable.
  • A variable is a named box holding a value, and a list holds many values in order.
  • A loop repeats a step for every item, and an if-statement does something only when a condition is true.
  • A function packages a recipe so you can reuse it with different inputs.
  • Most data work happens in tables (called data frames), where one line of code acts on a whole column.

Picture Sam, who runs a bike shop and has a spreadsheet of 36 months of sales. Sam wants to know the average sale, flag every month below some target, and do the same thing for next year's file without clicking through it all again. In a spreadsheet, each of those is a lot of clicking. In a program, it is a few lines you write once and run whenever you like.

That is the whole pitch. A program is a list of instructions, written so precisely that a computer can follow them without guessing. This lesson introduces the main ideas using Python, a popular language among economists, along with R and Stata. You will not become a programmer in one lesson. The goal is to read short programs, understand what they do and see why they help.

Why bother when spreadsheets exist?

Spreadsheets are great, as the earlier lesson showed. But they have limits. Repeating a messy cleaning job on a new file means redoing every click. Files with a million rows get slow. And it is hard to see exactly what was done to a number three tabs away.

Code fixes these. Every step is written down in order, so anyone can read it. You can run it on next year's file with no extra effort. And when you find a mistake, you fix one line and run it again, rather than hunting for the one cell you edited by hand. This is a big part of why code supports reproducible work.

You do not have to choose one tool forever. Many economists explore in a spreadsheet, then move to code when the job gets large or needs repeating.

Variables: named boxes

A variable is a name that holds a value. You create one with an equals sign, which in code means "store this", not "these are equal".

price = 400
units = 3
revenue = price * units
print(revenue)

The first line stores 400 under the name price. The second stores 3 under units. The third multiplies them and stores the answer, 1,200, under revenue. The last line shows it on the screen. The star is the multiplication sign. Python also uses / for division, + and - as you expect, and for powers, so 2 3 is 8.

Names should say what they hold. A name like revenue helps a reader. A name like x7 does not.

Lists: many values in order

Sam's monthly sales for the first six months, in thousands of dollars, can live in a list: a row of values in square brackets.

sales = [12, 15, 9, 14, 20, 10]
print(len(sales))
print(sum(sales))
print(sum(sales) / len(sales))

Here len counts the items, which gives 6. The built-in sum adds them: 12 + 15 + 9 + 14 + 20 + 10 = 80. Dividing 80 by 6 gives about 13.33. That is the average month, in thousands of dollars.

Python counts positions from zero. So sales[0] is 12, the first value, and sales[1] is 15. This trips up nearly every beginner. If you ask for sales[6] on a list of six items, you get an error, because the last position is 5.

The average, written as code
sum(sales) ÷ len(sales) = 13.33 sum(sales) = Total Add up every value in the list: 80. len(sales) = Count How many values there are: 6. 13.33 = Average The mean monthly sales, in thousands of dollars. sum(sales) ÷ len(sales) = 13.33 sum(sales) = Total Add up every value in the list: 80. len(sales) = Count How many values there are: 6. 13.33 = Average The mean monthly sales, in thousands of dollars.

A program often just writes down an idea you already know, in a form the computer can run.

Loops and conditions: repeating and choosing

Suppose Sam wants to mark every month below a target of 12 thousand dollars. A loop repeats a step for each item. An if-statement acts only when a condition is true.

target = 12
for s in sales:
    if s < target:
        print(s, "is below target")

Read it aloud. "For each value s in sales, if s is less than the target, print a message." The indented lines belong to the line above them; in Python, the spaces are not decoration, they are the structure.

Run it on the list [12, 15, 9, 14, 20, 10]. Twelve is not less than 12, so it is skipped. Fifteen is skipped. Nine is below, so it prints. Fourteen and twenty are skipped. Ten is below, so it prints. The output is two lines: 9 and 10 are below target.

Notice what the computer did not do. It never got bored, never skipped a row, and would work the same way on 6 months or 6 million.

What the loop does, step by step
1 Take the next value The loop picks the next number from the list: 12, then 15, then 9, and so on. 2 Test the condition Is the value less than the target of 12? 3 Act if true If yes, print the message. If no, do nothing. 4 Repeat Go back for the next value until the list runs out. Take the next value The loop picks the next number from the list: 12, then 15, then 9, and so on. 1 Test the condition Is the value less than the target of 12? 2 Act if true If yes, print the message. If no, do nothing. 3 Repeat Go back for the next value until the list runs out. 4

Functions: a recipe you can reuse

If you find yourself writing the same steps again, wrap them in a function. A function has a name, takes inputs and gives back a result.

def average(values):
    return sum(values) / len(values)

print(average([12, 15, 9, 14, 20, 10]))
print(average([100, 200]))

The word def starts the definition. The names in brackets are the inputs. The return line says what to give back. The first call gives about 13.33. The second gives (100 + 200) / 2 = 150. One recipe, two uses.

Functions also make your work easier to read. A line that says average(sales) tells the reader more than a line that repeats the arithmetic.

Tables of data: where the real work happens

Economic data is rarely one list. It is a table with columns such as date, sales and prices. In Python, a popular tool called pandas turns a table into a data frame. You do not need its full details yet; you need the idea. One line of code can act on an entire column.

import pandas as pd

df = pd.read_csv("sales.csv")
df["revenue"] = df["price"] * df["units"]
print(df["revenue"].mean())

Line by line: the first line loads the pandas tools. The second reads a file of comma-separated values (a CSV file) into a table called df. The third creates a new column, multiplying price by units for every row at once. The fourth prints the average of that column.

Suppose the file has these three rows.

price   units
400     3
250     4
100     10

Revenue becomes 400 × 3 = 1,200, then 250 × 4 = 1,000, then 100 × 10 = 1,000. The mean is (1,200 + 1,000 + 1,000) ÷ 3 = 3,200 ÷ 3 ≈ 1,066.67. You can check that by hand, which is exactly what you should do on your first few programs.

The cleaning work in the previous lesson also becomes a few lines here: dropping duplicates, converting text to numbers and merging two tables on a key all have simple commands.

Spreadsheet or code?
Spreadsheet Quick for small, one-off jobs You see every number at once Hand edits are easy to forget Slow to repeat on a new file Code Steps are written down in order Runs the same on a new file Handles very large tables Takes time to learn at first VS Spreadsheet Quick for small, one-off jobs You see every number at once Hand edits are easy to forget Slow to repeat on a new file Code Steps are written down in order Runs the same on a new file Handles very large tables Takes time to learn at first

A longer worked example: monthly changes

Let us put the pieces together on a question economists ask all the time. Sam's sales, in thousands of dollars, were 10, 12, 15 and 12 over four months. By how much did sales change, in percent, from each month to the next?

The idea is the one from time series basics: the change divided by the starting value, times 100. Written as a program, it looks like this.

sales = [10, 12, 15, 12]
for i in range(1, len(sales)):
    change = (sales[i] - sales[i - 1]) / sales[i - 1] * 100
    print(change)

The loop starts at position 1, not 0, because the first month has no month before it to compare with. For each position i, the code takes this month's value, subtracts last month's value, divides by last month's value and multiplies by 100.

Work it by hand. From 10 to 12 is a rise of 2, and 2 ÷ 10 × 100 = 20. From 12 to 15 is a rise of 3, and 3 ÷ 12 × 100 = 25. From 15 to 12 is a fall of 3, and -3 ÷ 15 × 100 = -20. So the program prints 20, 25 and -20.

Notice something worth a pause. Sales rose 20 percent, then 25 percent, then fell 20 percent. A fall of 20 percent does not undo a rise of 20 percent, because each percentage is measured from a different starting point. The program does not care, but you should. Checking a result against your own sense of the numbers is half the skill.

Sam's sales over four months
Sales ($ thousands) Sales 10 12 15 12 Month Sales ($ thousands) Sales 10 12 15 12 Month

The three changes the program prints are the slopes of these three line segments, expressed as a percent of the starting value.

Habits that make code easier to trust

A few small habits will save you hours.

Write comments. In Python, anything after a # sign on a line is ignored by the computer and meant for people. A comment such as "# percent change from last month" tells a reader, and your future self, what the next line is for.

Name things clearly. A variable called monthly_sales is better than ms. You will read your code far more often than you write it.

Run in small steps. Write two or three lines, run them and look at the result. Adding ten lines at once and then finding a bug means searching ten lines instead of two.

Read the error message from the bottom. Python prints a long trail, but the last line says what went wrong, such as a name that was not defined or a position outside a list. Often it points to the exact line.

Keep data and code apart. Leave raw files untouched and let the code read them. Then the same program can be run again on a fresh download.

Mistakes every beginner makes

Trusting output you have not checked. A program that runs is not a program that is right. Compute one answer by hand, as we did above, and compare. If 1,066.67 does not match what the code printed, something is wrong with the code or your understanding.

Off-by-one errors. Counting from zero causes many bugs. If a list has 6 items, the valid positions are 0 through 5.

Typos in names. Python treats Sales and sales as different names. The error message usually names the culprit; read it. Error messages are annoying, but they usually say what and where.

Mixing up = and ==. One equals sign stores a value. Two equal signs ask whether two things are equal. Writing if s = 12 is an error; the test is if s == 12.

Writing one giant block. Break work into small steps and run each one. If a long program fails, you will not know where to look.

Copying code you do not understand. Examples from the internet or from an AI assistant can be useful, but run them on a tiny test case first and read every line. Code that quietly does the wrong thing is worse than code that crashes.

The next lesson, summaries and regressions in code, builds on these pieces to describe data and fit simple models.

Words to know

Program a precise list of instructions that a computer follows in order.

Variable a name that holds a value, such as price = 400.

List an ordered collection of values, written in square brackets.

Loop a way to repeat a step once for each item in a collection.

Function a named, reusable recipe that takes inputs and returns a result.

Data frame a table of rows and columns that code can act on all at once.

CSV file a plain text file in which the values on each row are separated by commas.

Check yourself

  1. What does the line revenue = price * units store if price is 250 and units is 4?
  2. For the list sales = [12, 15, 9, 14, 20, 10], what is sales[0], and why is sales[6] an error?
  3. Using the same list and a target of 12, which values does the loop print as below target, and why is the first 12 skipped?
  4. Write the output of average([100, 200, 300]) and show the arithmetic.
  5. A data frame has price 400 with units 3 and price 100 with units 10. What is the mean revenue?
  6. Explain why running a program once on a tiny example you can compute by hand is a good habit.
Show the answers
  1. It stores 250 × 4 = 1,000 in revenue.
  2. sales[0] is 12 because counting starts at zero; the list has six items at positions 0 to 5, so position 6 does not exist.
  3. It prints 9 and 10; 12 is skipped because 12 < 12 is false (12 is equal to the target, not below it).
  4. (100 + 200 + 300) ÷ 3 = 600 ÷ 3 = 200.
  5. Revenues are 400 × 3 = 1,200 and 100 × 10 = 1,000; the mean is 2,200 ÷ 2 = 1,100.
  6. A program can run without errors and still be wrong; a small case you can check by hand shows whether the code does what you intended.

A free self-study program written for 4Economics with AI writing tools and not reviewed line by line by a person. It is not an accredited degree and awards no credit. Check anything you rely on against a textbook or primary source. Report an error.

In this unit: Working with data

  1. Spreadsheets for Economic AnalysisLearn to organize data in rows and columns, write formulas for growth and averages, and avoid common spreadsheet traps.10 min
  2. Charts That Tell the TruthLearn how axes, scales and choices of chart type can mislead, and how to draw honest charts of economic data.10 min
  3. Cleaning and Merging DataRaw data is messy. Learn to find and fix common problems, then join two tables safely on a shared key.12 min
  4. A First Look at Programming for Data AnalysisMeet variables, lists, loops, functions and tables in Python, using small economic examples you can follow line by line.11 min
  5. Summaries and Regressions in CodeUse a few lines of Python to describe a data set, fit a straight line, and read the results without being fooled.11 min
  6. Reproducible Work: Files, Notes and VersionsOrganize files, write down your steps and save versions so that you, or anyone else, can redo an analysis and get the same answer.11 min
  7. Time Series Basics: Trends, Growth Rates and Moving AveragesLearn to read data that comes in time order: find the trend, compute growth rates correctly, and smooth noise with a moving average.10 min
  8. Presenting Data Findings to Non-ExpertsTurn an analysis into a clear message for busy readers: lead with the answer, choose one chart, and be honest about doubt.10 min

In the news