Chapter 1: Python Programming Fundamentals#
Python is like a Swiss army knife for modern data work. It reads almost like English, yet it can handle huge amounts of data easily. In this chapter, we’ll learn the basics you need to write clear, correct Python code. You’ll be able to do everything from quick calculations to complex financial models.
The Big Picture#
Every program, no matter how complex, is built from a few simple ideas: storing values, making choices, and repeating actions. This chapter gives you those building blocks in Python’s own way. By the end, you’ll be able to write scripts that work with numbers and text, make decisions, loop over data, and use short, powerful tools — the exact skills you’ll use when analyzing financial data or testing a trading idea.
Python’s Philosophy: Readability and Dynamic Typing#
Python was designed so that code is easy to read. Instead of using curly braces or special words to mark blocks, Python uses indentation (spaces at the start of a line) to group lines together. Every line inside an if, a loop, or a function must be indented by the same number of spaces (usually four). This makes the code look like the logic it describes.
if temperature > 30:
print("It's a hot day.")
print("Remember to hydrate.")The colon at the end of the if line tells Python that a new block is starting. The two print calls are indented — they belong to the if. When we return to the left margin, the block ends. If the indentation is not consistent, Python will give you a SyntaxError, so you learn to keep it neat from the start.
Python is also dynamically typed: you don’t have to say what type a variable is. The same variable name can hold an integer now and a string later. The type belongs to the value, not to the variable name.
x = 42 # x is an integer
x = "forty-two" # now x is a string — perfectly legalThis flexibility lets you write quick, experimental code without extra steps. Behind the scenes, Python still keeps track of types carefully — you just don’t have to write them out.
Dynamic typing: A language feature where a variable can hold different types of values at different times; the type is checked while the program runs, not before.
📝 Section Recap: Python uses indentation to define code blocks, making programs visually structured and readable. Variables are dynamically typed, so you can assign any kind of value to a name without declaring its type.
Core Data Types: Numbers, True/False, and Text#
Every piece of data you work with has a type. Python’s built‑in types for numbers, true/false values, and text are the basic building blocks of almost every script.
Integers, Floats, and Booleans#
An integer (int) is a whole number, positive or negative, without a decimal point. Python integers can be as big as your computer’s memory allows, so you never have to worry about them getting too large when you multiply huge numbers.
big = 2 ** 1000 # a 302‑digit number, computed instantlyA floating‑point number (float) is a number with a decimal point, stored in a fixed amount of memory (usually 64 bits). This means floats can cover a huge range but with limited precision. Small rounding errors are normal, just like on a calculator.
0.1 + 0.2 # yields 0.30000000000000004, not exactly 0.3For financial work where exact decimal math matters, Python provides the decimal module. Its Decimal objects let you control precision and rounding, avoiding the tiny errors that floats can cause.
from decimal import Decimal, getcontext
getcontext().prec = 6
price = Decimal('19.99')
tax = Decimal('0.07')
total = price + price * tax # exactly 21.3893, with the precision you setA boolean (bool) is simply True or False. Booleans are a kind of integer: True acts like 1 and False acts like 0 in math, but they represent logical truth.
Boolean: A value that is either
TrueorFalse, used to control branching and loops.
Strings#
A string (str) is a sequence of characters, created by putting text in single or double quotes. Strings are immutable — once you create one, you cannot change a character directly; you make a new string instead.
ticker = "AAPL"
exchange = 'NASDAQ'You can join strings with + and repeat them with *:
line = "-" * 40 # 40 hyphensPython treats strings as sequences, so you can pick out characters and slices:
ticker[0] # 'A'
ticker[1:3] # 'AP'String: An unchangeable sequence of characters, used for text.
📝 Section Recap: Python gives you integers that can be as large as you need, floats for approximate decimals, the
Decimalmodule for exact decimal math, booleans for true/false logic, and strings for text. These five types are the foundation of working with data.
String Formatting and Pattern Matching#
Real‑world data rarely comes in the exact form you need. Python offers several ways to build strings from variables, and a powerful mini‑language — regular expressions — for searching and cleaning text.
Building Strings with Variables#
The oldest way is the % operator, borrowed from the C language’s printf:
name = "Alice"
shares = 150
msg = "%s bought %d shares" % (name, shares)The placeholder %s expects a string, %d an integer, and %f a float. This style still appears in older code, but it can cause errors if the types don’t match.
A more flexible way is the str.format() method, which uses curly braces {} as placeholders:
msg = "{} bought {} shares".format(name, shares)
msg = "{0} bought {1} shares today, {0}!".format(name, shares) # reuse by index
msg = "{trader} bought {qty} shares".format(trader=name, qty=shares) # named fieldsThis separates the order of arguments from their position in the string and handles any type automatically.
Modern Python also supports f‑strings (formatted string literals), which put expressions directly inside curly braces:
msg = f"{name} bought {shares} shares at {price:.2f}"F‑strings are short, fast, and the recommended way to build strings today. The colon inside the braces sets the format — :.2f rounds a float to two decimal places.
Pattern Matching with Regular Expressions#
A regular expression (regex) is a pattern that describes a set of strings. Python’s re module lets you search, pull out, and replace text using these patterns.
import re
text = "Contact: alice@example.com or bob@finance.org"
pattern = r"[\w.]+@[\w.]+"
emails = re.findall(pattern, text) # ['alice@example.com', 'bob@finance.org']r"..."marks a raw string so backslashes are treated as normal characters.\wmatches any word character (letters, digits, underscore).+means “one or more”.@matches itself.re.findallreturns all non‑overlapping matches.
Regex is extremely useful for cleaning messy CSV files, checking user input, or reading log files. The syntax looks dense, but a few building blocks — character classes, quantifiers, anchors — cover most everyday needs.
Regular expression: A string that defines a search pattern, used to match, extract, or replace parts of text.
📝 Section Recap: Python gives you multiple ways to put variables into strings, with f‑strings being the modern favorite. The
remodule adds regular expressions, a compact language for finding and working with text patterns — essential for data cleaning.
Control Flow: Making Decisions and Repeating Actions#
Programs become useful when they can make decisions and repeat actions. Python’s control‑flow keywords read like natural English.
Branching with if‑elif‑else#
The if statement tests a condition. If it’s true, the indented block runs. You can chain multiple conditions with elif (short for “else if”) and provide a fallback with else.
price = 105.0
if price > 100:
signal = "sell"
elif price > 95:
signal = "hold"
else:
signal = "buy"Conditions can combine with and, or, and not. Python uses short‑circuit evaluation: it stops checking as soon as the result is clear.
Loops: for and while#
A for loop goes through any sequence — a list, a string, a range of numbers, or even lines in a file.
prices = [101.2, 99.8, 104.5]
for p in prices:
print(f"Price: {p:.2f}")The built‑in range() function creates a sequence of integers, often used to repeat an action a set number of times:
for i in range(5): # 0, 1, 2, 3, 4
print(i)A while loop keeps running as long as a condition stays true. It’s perfect when you don’t know in advance how many times you need to repeat.
balance = 1000
rate = 1.05
years = 0
while balance < 2000:
balance *= rate
years += 1
# After the loop, years tells you how long it took to double.Be careful: if the condition never becomes false, you’ll get an infinite loop. Always make sure the loop body moves the state toward the exit condition.
You can stop a loop early with break or skip the rest of the current iteration with continue.
forloop: A control structure that runs a block of code once for each item in a sequence.
whileloop: A control structure that repeats a block as long as a condition is true.
📝 Section Recap: Use
if‑elif‑elseto make decisions,forloops to go through known sequences, andwhileloops to repeat until a condition changes. Together they let you express any decision or repetition logic.
Functional Tools: Lambdas, Map, Filter, Reduce#
Python supports a functional style — treating functions as objects that you can pass around, create on the fly, and apply to whole collections. This style often leads to short, clear data pipelines.
Lambda Expressions#
A lambda is a small, unnamed function that can only have a single expression. You define it with the lambda keyword, a list of parameters, a colon, and the expression to evaluate.
square = lambda x: x * x
square(5) # 25Lambdas are handy when you need a short function for just one place, like a sorting key:
trades = [("AAPL", 150), ("GOOG", 2800), ("MSFT", 300)]
trades.sort(key=lambda t: t[1]) # sort by priceYou could write a normal def for this, but a lambda keeps the logic right where it’s used.
map, filter, and reduce#
These three built‑ins let you change, select, and combine data without writing loops.
map(function, iterable)applies a function to every item and gives back an iterator of the results.
nums = [1, 2, 3, 4]
squared = map(lambda x: x**2, nums)
list(squared) # [1, 4, 9, 16]filter(function, iterable)keeps only the items for which the function returnsTrue.
even = filter(lambda x: x % 2 == 0, nums)
list(even) # [2, 4]reduce(function, iterable[, initial])(from thefunctoolsmodule) repeatedly applies a function of two arguments, combining the sequence into a single value.
from functools import reduce
total = reduce(lambda a, b: a + b, nums) # 10These tools shine when you chain operations. For example, to sum the squares of even numbers:
sum_of_even_squares = reduce(
lambda a, b: a + b,
map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums))
)In practice, list comprehensions often replace map and filter with more readable syntax, but the functional approach is still useful when you need to pass a transformation as an argument to another function or when working with large data streams lazily.
Lambda: A small unnamed function defined with the
lambdakeyword, made of a single expression.
map: Applies a function to each element of an iterable, giving back an iterator of results.
filter: Returns an iterator over elements of an iterable for which a function returnsTrue.
reduce: Repeatedly applies a two‑argument function to the items of an iterable, combining them into a single value.
📝 Section Recap: Lambdas let you create tiny throw‑away functions.
mapandfilterchange and select data without loops, whilereducecombines sequences. These functional tools work alongside loops and comprehensions, giving you multiple ways to express data transformations.
Summary#
We started with Python’s clean, indentation‑based syntax and the freedom of dynamic typing. Then we met the core data types — integers that can be as big as you need, floats for approximate decimals, the Decimal module for exact money math, booleans for logic, and strings for text. You learned how to put variables into strings with %, .format(), and f‑strings, and how to search messy text with regular expressions. Control flow gave you the power to make decisions and loop over data, while lambdas, map, filter, and reduce introduced a short, functional way to process collections. All of these pieces are the everyday vocabulary of a Python data analyst or quant developer.
| Key idea | What it means (plain English) | Why it matters |
|---|---|---|
| Indentation | Code blocks are defined by consistent spaces at the start of lines, not braces. | Makes code easy to read and prevents common bracket mistakes. |
| Dynamic typing | Variables don’t have a fixed type; they can hold any kind of value. | Speeds up writing scripts and lets you reuse names easily. |
| Arbitrary‑precision integers | Whole numbers can be as large as needed, limited only by memory. | No overflow errors when computing large factorials, powers, or financial totals. |
Decimal module |
Provides exact decimal math with user‑controlled precision. | Avoids the tiny floating‑point errors that can mess up financial calculations. |
String formatting (%, .format(), f‑strings) |
Ways to put variables and expressions inside text. | Essential for creating readable output, log messages, and reports. |
| Regular expressions | A pattern language for matching and pulling out text. | Quickly cleans, checks, and reads unstructured data like emails, dates, or logs. |
if‑elif‑else |
Branching logic that runs code based on conditions. | Implements decision rules, such as trading signals or risk limits. |
for and while loops |
Structures that repeat code over sequences or while a condition is true. | Automates repetitive tasks like going through price lists or simulating account growth. |
| Lambda expressions | Small, unnamed functions written in a single line. | Create quick logic for sorting, mapping, or filtering without defining a full function. |
map, filter, reduce |
Functions that apply an operation to every element, select elements, or combine them into one value. | Express data transformations concisely, often replacing explicit loops for clarity. |