Lesson 3

Variables, Values, Types, Strings, and Dates

Big question

How does Python know whether a value is a price, a label, a date, or a logical condition?

Lesson progress

Complete checkpoints as you learn

0% complete0 checkpoint streak
Progress tracking available after sign-in. Sign in to save your work.
Big question
Concept
Activity
Quiz

Learning objectives

  • Create variables with meaningful names.
  • Work with integers, floats, strings, booleans, and None.
  • Format text and numeric results.
  • Parse and compare dates safely.
  • Prerequisites: Chapter 2.
  • Key terms: variable, object, type, boolean, None, datetime.

Simple explanation

Assignment binds a name to an object. The statement rate = 0.045 does not put a value into a permanent box called rate; it creates a floating-point object and lets the name refer to it. This matters when objects are mutable, but the beginner rule is simpler: choose names that carry economic meaning, avoid spaces and punctuation, and reserve uppercase names for constants only when that convention genuinely helps. Python is dynamically typed, so the value determines the type at runtime.

Key terms

Create variables with meaningful names
A core idea in Chapter 3 that students apply carefully in economic analysis.
Work with integers, floats, strings, booleans, and None
A core idea in Chapter 3 that students apply carefully in economic analysis.
Format text and numeric results
A core idea in Chapter 3 that students apply carefully in economic analysis.
Parse and compare dates safely
A core idea in Chapter 3 that students apply carefully in economic analysis.
Prerequisites: Chapter 2
A core idea in Chapter 3 that students apply carefully in economic analysis.
Key terms: variable, object, type, boolean, None, datetime
A core idea in Chapter 3 that students apply carefully in economic analysis.

Analytical workflow

Question+data+assumptions+transparentPython>evidenceQuestion + data + assumptions + transparent Python -> evidence

Interpret the expression in words and units before using it in a claim.

Example

Interpretation. The format specification changes presentation, not the stored value.

Prerequisites

  • Complete the preceding course chapters or review their summaries as needed.

Full theory and examples

3.2

Names point to objects

Assignment binds a name to an object. The statement rate = 0.045 does not put a value into a permanent box called rate; it creates a floating-point object and lets the name refer to it. This matters when objects are mutable, but the beginner rule is simpler: choose names that carry economic meaning, avoid spaces and punctuation, and reserve uppercase names for constants only when that convention genuinely helps. Python is dynamically typed, so the value determines the type at runtime.

3.3

Types are analytical constraints

A string such as "2.5" looks like a number to a human but cannot be averaged until it is converted. A date stored as plain text does not automatically understand calendar order. Type conversion is therefore part of data validation. Floating-point numbers also have finite binary precision, so exact equality can be unreliable for some decimal calculations. Financial accounting may require Decimal; most econometric work uses floating point and numerical tolerances.

3.4

Dates carry frequency and meaning

Calendar data require explicit parsing. The same text can be interpreted differently across countries, and a monthly observation may represent an average, a period end, or a reference month. Python’s datetime and pandas date tools support arithmetic, sorting, and resampling, but the analyst must still document the observation convention. A timestamp is not merely a label: it determines ordering, lags, trading-day alignment, and forecast origin.

3.5

Python demonstrations

3.5.1

Demonstration 3.1: Types and formatted output

Verified output

Interpretation. The format specification changes presentation, not the stored value.

3.5.2

Demonstration 3.2: Parse and compare dates

Verified output

Interpretation. ISO dates avoid day-month ambiguity and support calendar arithmetic.

3.6

Visual evidence

3.7

Reference table

Why This Matters

Correct types prevent quiet errors in sorting, aggregation, filtering, and model construction.

Common Mistake

Using a numeric-looking identifier, such as a postal code, as a number. Leading zeros and categorical meaning may be lost.

Ceteris LAB Tip

Inspect type(value) when an operator behaves strangely. The error often belongs to the input type, not the formula.

R-to-Python / Source Bridge

The introductory source material used R assignments and raw numeric dates. This chapter preserves the idea of named objects while adding explicit type and calendar discipline.

Table 3. Chapter reference.
TypeExampleUse
int12counts and discrete quantities
float0.045rates and measurements
str“Canada”labels and identifiers
boolTrueconditions and filters
NoneNoneintentional absence
datetime2026-08-15calendar operations

Visual evidence

Figure 3. Common Python scalar types and example values.
Figure 3. Common Python scalar types and example values.

Additional Python demonstrations

Live Python

Source demonstration 2

Source demonstration 2

Stdout

Run Python to see results here.

Status / stderr

Ready to run Python in your browser.

Line-by-line guide

  1. Line 1Load a Python library needed for data work or regression.
  2. Line 3Create or update a Python object used in the analysis.
  3. Line 4Create or update a Python object used in the analysis.
  4. Line 5Display a result so students can inspect the output.
  5. Line 6Display a result so students can inspect the output.

Verified source output

float Canada: 2.75%, n=120, monthly=True
226 True
float
Canada: 2.75%, n=120, monthly=True
226
True

Interpretation. The format specification changes presentation, not the stored value.

Interpretation. ISO dates avoid day-month ambiguity and support calendar arithmetic.

Guided practice

  1. 1Re-run Demonstration 3.1 and change one input while keeping the analytical question fixed.
  2. 2Explain in two sentences how the output supports, or fails to support, the chapter opening question.
  3. 3Add one validation check that would prevent a plausible error.

Exercises

  1. 1Create variables for a bond price, maturity year, issuer name, and default flag.
  2. 2Convert the string “3.25” to a float and divide it by 100.
  3. 3Format 1234567.891 as currency with commas and two decimals.
  4. 4Calculate the days between two ISO dates.

Source and downloads

Chapter 3 of Fundamentals of Python for Financial Econometrics by Mohammad Safavi, Ph.D.. The lesson is an original Ceteris Lab web adaptation of the supplied publication package.

Live Python

Variables, Values, Types, Strings, and Dates: live Python

Variables, Values, Types, Strings, and Dates: live Python

Stdout

Run Python to see results here.

Status / stderr

Ready to run Python in your browser.

Line-by-line guide

  1. Line 1Create or update a Python object used in the analysis.
  2. Line 2Create or update a Python object used in the analysis.
  3. Line 3Create or update a Python object used in the analysis.
  4. Line 4Create or update a Python object used in the analysis.
  5. Line 6Display a result so students can inspect the output.
  6. Line 7Display a result so students can inspect the output.

Python walkthrough

  1. 1`country = "Canada"`: Creates or updates a named object used by later steps.
  2. 2`policy_rate = 0.0275`: Creates or updates a named object used by later steps.
  3. 3`observations = 120`: Creates or updates a named object used by later steps.
  4. 4`is_monthly = True`: Creates or updates a named object used by later steps.
  5. 5`print(type(policy_rate).__name__)`: Displays a result so it can be checked and interpreted.
  6. 6`print(f"{country}: {policy_rate:.2%}, n={observations}, monthly={is_monthly}")`: Displays a result so it can be checked and interpreted.

Live notebook

Run this lesson as a notebook

Open an editable notebook cell-by-cell, run Python in the browser, and download the `.ipynb` file for later.

Related dataset

Ceteris Lab teaching sample

Estimated time

25 to 40 min

Packages

pandas, numpy

Expected output

Printed Python results that can be compared with the lesson explanation.

Learning goals

  • Load and inspect Ceteris Lab teaching sample.
  • Run the Python cells connected to Variables, Values, Types, Strings, and Dates.
  • Interpret the output using Create variables with meaningful names and Work with integers, floats, strings, booleans, and None.

Common errors

  • File not found: check that wage_sample.csv is installed or use the course data folder.
  • Package import error: use the browser notebook first, then download for local Jupyter if your local packages differ.
  • Column name error: compare your variable names with the dataset variables listed for this notebook.

Dataset path helper

import pandas as pd

df = pd.read_csv("/data/wage_sample.csv")
df.head()

Interactive activity

Chapter 3 interactive

Reproducible Python decision lab

Evidence strength: 55%
Fragile workflowReproducible workflow

Which step should come before trusting a successful Python run?

Immediate feedback

Choose a decision, then test how the claim changes as evidence becomes stronger or weaker.

Try it yourself

Write one plain-English sentence explaining the main idea from this lesson.

Common mistakes

Check these before you move on.

Return to the lesson assumptions, units, diagnostics, and source evidence to replace this shortcut with a defensible interpretation.

Quick quiz

Which statement best answers the Chapter 3 opening question: How does Python know whether a value is a price, a label, a date, or a logical condition?

Quick quiz

Which practice should be avoided when applying Variables, Values, Types, Strings, and Dates?

Quick quiz

What is the most defensible way to interpret the Python demonstration?

Quick quiz

Why does Chapter 3 matter in an applied econometrics workflow?

Key takeaway

Variables name objects; types determine valid operations. Formatting controls display without changing the underlying value. Dates should be parsed explicitly and documented.