How programs store information, represent different kinds of data, build expressions from values and operators, and track changing state over time
Every program that does anything useful has to remember information. It stores a name, a score, a temperature, a password, a running total. It works with that information — comparing values, adding numbers, joining words together, checking whether something is true or false. This chapter is about how programs do that: through variables, types, expressions, and the idea of state.
These ideas are not unique to Python or to any one language. Variables, values, types, expressions, and assignment appear in Python, JavaScript, Java, C, Rust, and nearly every other language you will encounter. The syntax changes from language to language, but the underlying logic stays the same. This chapter uses Python-style examples because Python's syntax is clear and readable for learning. The goal, however, is not to memorize Python. The goal is to build the mental model that will carry you through Chapter 8 and every programming course beyond this one.
A program needs to track a player's score in a game. The score starts at zero, increases when the player earns points, and decreases when the player loses a life. How should the program remember this value? How does it update it? How does it display it on screen? By the end of this chapter, you will know exactly how — and why the same pattern applies to prices, temperatures, names, usernames, and every other piece of information a program manages.
A value is a piece of information a program can use. Values come in many forms: the number 42, the word "hello", the measurement 3.14, or the truth-or-false choice True. Every piece of data in a program is a value. Values by themselves are temporary — if a program computes a result and nothing stores it, that result disappears as soon as the line finishes executing.
A variable is a named storage location that holds a value. When a program creates a variable, it gives a name to a piece of memory so that value can be referred to later. Think of a variable as a labeled box: the label is the variable's name, and the contents of the box are the variable's value. The box can hold different contents at different times.
variable name: score
variable value: 95
A program can read from the box (look at the score), write to the box (change the score), or pass the box's contents somewhere else (display the score, or add it to another number).
In Python, variable names can contain letters, digits, and underscores. Names must start with a letter or underscore — not a digit. Names are case-sensitive: score, Score, and SCORE are three different variables. Names should be descriptive: total_score is clearer than ts.
| Good Variable Names | Poor Variable Names | Why Poor? |
|---|---|---|
age | x | Unclear meaning |
first_name | temp2 | Ambiguous — temperature? temporary? |
temperature_celsius | a1b2c3 | Unreadable |
number_of_students | 1score | Starts with a digit — invalid |
is_logged_in | IsLoggedIn | Inconsistent style; not conventional Python |
The habit of writing clear variable names is one of the most valuable habits in programming. It makes programs readable — for other programmers, and for your future self who may return to the code months later with no memory of what x was supposed to mean.
first_name · 2ndScore · total_cost · my variable · _count · MAX
An assignment statement stores a value into a variable. In Python, the assignment operator is a single equals sign (=). The left side is always a variable name; the right side is always a value or expression that produces a value. The = sign does not mean "equals" in the mathematical sense — it means "store this value into this variable."
age = 17 score = 100 name = "Jordan" temperature = 98.6 is_active = True
After these five lines execute, five variables exist, each holding a value of a different type.
A variable can be reassigned as many times as needed. Each assignment replaces the previous value entirely — the earlier value is gone.
score = 100 score = 95 score = 87 print(score) # Output: 87
An important rule: the right side of an assignment is fully evaluated before anything is stored. This makes the pattern x = x + 1 valid — and very common in programming.
x = 5 x = x + 1 # look up x (5), add 1, get 6, store 6 in x print(x) # Output: 6
In mathematics, x = x + 1 is impossible — no number equals itself plus one. In programming, = is not equality; it is an instruction. It means: "evaluate the right side, then store the result in the variable on the left." The earlier value of x is used in computing the new value, then replaced.
A trace table records the values of variables through each step of a program's execution. Tracing is the most reliable way to understand what a program does and to find errors.
a = 10
b = 3
a = a + b
b = a - b
print(a)
print(b)
| Step | Statement | a | b |
|---|---|---|---|
| 1 | a = 10 | 10 | — |
| 2 | b = 3 | 10 | 3 |
| 3 | a = a + b | 13 | 3 |
| 4 | b = a - b | 13 | 10 |
Build a trace table for each program and write the output.
x = 8 / y = 3 / x = x * y / print(x)a = 20 / b = a // 3 / c = a % 3 / print(b) / print(c)name = "Alex" / greeting = "Hello, " + name / print(greeting)An integer (type int) is a whole number with no decimal point. Integers can be positive, negative, or zero. They are used for counting, indexing, and any situation where fractional values do not make sense — you cannot have 2.7 students.
students = 30 temperature = -5 items = 0 year = 2025
A float (type float) is a number with a decimal point, representing real-world measurements that are not always whole numbers.
price = 4.99 height = 1.75 pi = 3.14159
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
** | Exponentiation | 2 ** 4 | 16 |
// | Integer division | 7 // 3 | 2 |
% | Remainder (modulo) | 7 % 3 | 1 |
/ | Division (float result) | 7 / 3 | 2.333... |
Integer division (//) divides and keeps only the whole number portion, discarding the remainder. 7 // 3 gives 2 because 3 goes into 7 twice with something left over. The remainder operator (%) gives what is left after integer division. 7 % 3 gives 1 because 7 = (3 × 2) + 1.
minutes = 137
hours = minutes // 60 # 137 // 60 = 2
remaining = minutes % 60 # 137 % 60 = 17
Dividing by zero causes a ZeroDivisionError and stops the program. Always ensure the divisor cannot be zero before dividing.
Mixing division types: 7 / 2 produces 3.5 in Python — not 3. If you want integer division, use 7 // 2.
15 + 4 * 320 // 620 % 63 ** 3100 / 8100 // 817 % 52 ** 10Also: A program receives 245 seconds. Using // and %, compute the full minutes and remaining seconds. Show your work.
A string is a sequence of characters — letters, digits, punctuation, spaces, or any other symbol — treated as text. Strings are enclosed in quotation marks. Both single quotes and double quotes work in Python; the convention is to be consistent. The value "42" and the value 42 are completely different: one is a string, one is an integer.
| Operation | Operator | Example | Result |
|---|---|---|---|
| Concatenation (join) | + | "Hello" + " World" | "Hello World" |
| Repetition | * | "-" * 10 | "----------" |
| Length | len() | len("hello") | 5 |
| Indexing | [] | "hello"[1] | "e" |
A string is a sequence of individual characters, each at a numbered position called an index. In Python — and most languages — indexes start at zero, not one.
String: a l g o r i t h m
Index: 0 1 2 3 4 5 6 7 8
The string "algorithm" has 9 characters. The first is at index 0; the last is at index 8. This off-by-one pattern appears throughout programming — lists, arrays, and all sequences behave the same way.
word = "algorithm" print(word[0]) # a print(word[4]) # r print(word[8]) # m print(len(word)) # 9
An f-string (formatted string literal) lets you embed variable values directly inside a string. Place an f before the opening quote and put variable names or expressions inside {}.
name = "Jordan" score = 94 print(f"Student: {name}, Score: {score}") # Output: Student: Jordan, Score: 94
"42" is a string. 42 is an integer. You cannot mix them with + directly. Writing "Score: " + 94 will cause a TypeError. Use an f-string or str(94) to convert first.
len("computer")"ab" * 4"Hello" + " " + "there""science"[3]"science"[0]len("") Also: Write an f-string that displays a person's full name and age on one line. Define the variables first, then write the print statement.
A Boolean (named after mathematician George Boole) is a value that is either True or False — exactly two values, nothing else. Booleans represent yes/no, on/off, and present/absent conditions. They are most often produced by comparison expressions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 5 > 10 | False |
<= | Less than or equal to | 5 <= 5 | True |
>= | Greater than or equal to | 3 >= 7 | False |
Three operators combine or modify Boolean values: and (True only if both sides are True), or (True if at least one side is True), and not (reverses the value).
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
= is assignment: stores a value into a variable. It is an instruction.
== is comparison: checks whether two values are equal and produces True or False.
Writing = when you mean == — or vice versa — causes bugs that can be difficult to find. This is one of the most common errors beginners make.
10 > 53 == 3.07 != 7True and FalseTrue or Falsenot True5 > 3 and 10 < 45 > 3 or 10 < 4not (5 == 5)not False or FalseAn expression is any combination of values, variables, and operators that a program can evaluate to produce a single value. 3 + 4 evaluates to 7. score * 2 evaluates to twice the current value of score. age >= 18 evaluates to True or False. Every expression produces exactly one value, which can be stored, passed to a function, or used inside another expression.
When an expression contains multiple operators, evaluation follows precedence rules — similar to the order of operations in arithmetic. Higher-precedence operators evaluate first.
| Priority | Operators |
|---|---|
| Highest | ** (exponentiation) |
Unary - (negation) | |
*, /, //, % | |
+, - | |
Comparisons: <, >, <=, >=, ==, != | |
not | |
and | |
| Lowest | or |
Parentheses are always evaluated first and make intent clear. (2 + 3) * 4 is unambiguous even if the reader does not know precedence rules. Parentheses also make code easier to read, which is just as important as making it correct.
2 + 3 * 4 and (2 + 3) * 4. Explain why they differ.2 + 3 * 4 → 2 + 12 → 14 (multiplication first)
(2 + 3) * 4 → 5 * 4 → 20 (parentheses first)
discount = 0.10
original_price = 49.99
final_price = original_price * (1 - discount)
# = 49.99 * (1 - 0.10)
# = 49.99 * 0.90
# = 44.991
5 + 3 * 2(5 + 3) * 22 ** 3 + 110 - 4 / 215 % 4 + 13 > 1 and 4 < 2not 5 == 53 > 1 or 4 < 2The print() function displays output to the screen. It can take one value, multiple comma-separated values, or an f-string. By default, it separates multiple values with a space and ends with a newline.
print("Hello!") print(42) print(3.14) print("Name:", name, "Age:", age)
The input() function pauses the program and waits for the user to type something. Whatever is typed is returned as a string — always a string, regardless of what the user typed. The argument to input() is the prompt shown to the user.
name = input("What is your name? ") print("Hello,", name)
Because input() always returns a string, you must convert the result if you need a number. If the user types 17, you receive the string "17" — you cannot do arithmetic on it directly without converting it first.
age = int(input("Enter your age: ")) next_year = age + 1 print(f"Next year you will be {next_year}")
If the user types "seventeen" when the program expects an integer, int("seventeen") will fail with a ValueError. Handling this safely requires error handling techniques covered in later courses. For now, always ensure you convert input to the correct type before performing operations on it.
F = (C * 9/5) + 32. What conversion function do you need to apply to the input?age = input("Age: ") and then print(age + 1). What error will this produce and why?Type conversion (also called casting) changes a value from one type to another. Python provides built-in functions for the most common conversions.
| Function | Converts To | Example | Result |
|---|---|---|---|
int() | Integer | int("42") | 42 |
float() | Float | float("3.14") | 3.14 |
str() | String | str(99) | "99" |
bool() | Boolean | bool(0) | False |
Note that int() applied to a float truncates — it removes the decimal portion without rounding. int(3.9) produces 3, not 4. int(-3.9) produces -3, not -4.
Every value has a Boolean interpretation. Falsy values — those that behave like False — include: 0, 0.0, "" (empty string), None, and empty collections. Everything else is truthy.
bool(0) → False bool(1) → True bool("") → False bool("hi") → True
price_text = "24.99"
quantity_text = "3"
price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print(f"Total: ${total:.2f}")
price = 24.99 (float)
quantity = 3 (int)
total = 24.99 * 3 = 74.97
:.2f rounds the display to 2 decimal places
Part A: Identify the type of each value (int, float, str, or bool).
42"42"3.14True"True"0""-7.5Part B: What does each conversion produce?
int(3.9)int(-3.9)float("7")str(100)bool(0)bool(-5)int("hello")bool("")A program's state is the collection of all variables and their current values at any moment during execution. State changes as the program runs — variables are created, values are updated, and conditions shift. Understanding state is essential for reading programs and predicting output. When you trace a program, you are tracking its state step by step.
counter = 0
total = 0
counter = counter + 1
total = total + 10
counter = counter + 1
total = total + 15
print(counter)
print(total)
| Statement | counter | total |
|---|---|---|
| counter = 0 | 0 | — |
| total = 0 | 0 | 0 |
| counter = counter + 1 | 1 | 0 |
| total = total + 10 | 1 | 10 |
| counter = counter + 1 | 2 | 10 |
| total = total + 15 | 2 | 25 |
An accumulator is a variable that builds up a value over time through repeated addition or other operations. The pattern total = total + value is so common that Python provides shorthand operators.
| Shorthand | Equivalent | Effect |
|---|---|---|
x += 5 | x = x + 5 | Add 5 to x |
x -= 3 | x = x - 3 | Subtract 3 from x |
x *= 2 | x = x * 2 | Multiply x by 2 |
x /= 4 | x = x / 4 | Divide x by 4 |
x //= 2 | x = x // 2 | Integer divide x by 2 |
x %= 3 | x = x % 3 | Replace x with x mod 3 |
score = 0 score += 10 # score is now 10 score += 25 # score is now 35 score -= 5 # score is now 30 print(score) # 30
Swapping the values of two variables is a classic programming task. A naive approach fails because the first assignment overwrites the original value before the second assignment can read it. The correct approach uses a temporary variable to preserve the original value.
a = 10
b = 20
a = b # a is now 20 — original value of a is LOST
b = a # b is now 20, not 10
# Result: a = 20, b = 20 (WRONG)
a = 10
b = 20
temp = a # save a's original value
a = b # a gets b's value (20)
b = temp # b gets original a's value (10)
# Result: a = 20, b = 10 (CORRECT)
Python allows a cleaner swap using tuple unpacking: a, b = b, a. This swaps the values in one line. The right side is fully evaluated before any assignment occurs, so neither value is lost. This is elegant Python — but the temporary variable method remains important to understand.
Build a trace table and write the final output for each program.
score = 0 / score += 10 / score += 25 / score -= 5 / score *= 2 / print(score)
x = 8 / y = 3 / x, y = y, x / print(x) / print(y)
p = 5 / q = 9 / p = q / q = p / print(p, q)
A program is a list of instructions that execute from top to bottom, one at a time. Reading a program means following along and tracking what happens at each step. The habits of a good code reader: start at the top; for each line, ask what it does to the program's state; track variable values in a trace table; predict what each print() will produce before running the code. Do not run the code first — predict the output, then verify.
print("Simple Calculator") x = float(input("Enter first number: ")) y = float(input("Enter second number: ")) total = x + y difference = x - y product = x * y print(f"Sum: {total}") print(f"Difference: {difference}") print(f"Product: {product}")
Sum: 10.0
Difference: 2.0
Product: 24.0
first = input("First name: ") last = input("Last name: ") full_name = last + ", " + first print(f"Hello, {full_name}!")
first = "Alex"
last = "Rivera"
full_name = "Rivera" + ", " + "Alex" = "Rivera, Alex"
Output: Hello, Rivera, Alex!
celsius = float(input("Enter temperature in Celsius: ")) fahrenheit = (celsius * 9 / 5) + 32 print(f"{celsius}°C = {fahrenheit}°F")
100 * 9 = 900
900 / 5 = 180.0
180.0 + 32 = 212.0
Output: 100.0°C = 212.0°F
Predict the output of each program without running it. Then verify.
Program A:
a = 10 b = 4 c = a + b a = c - a print(a) print(b) print(c)
Program B:
score = 0 score += 10 score += 25 score -= 5 score *= 2 print(score)
Program C:
word = "science" print(word[0]) print(len(word)) print(word[3]) print("cs " * 3)
Program D:
x = True y = False print(x and y) print(x or y) print(not x) print(x and not y)
= stores a value into a variable. The right side evaluates first. Reassignment replaces the previous value. Trace tables track variable state step by step.+, -, *, **, /, //, and %. Integer division and remainder are especially useful for time, indexing, and parity checks.+; repetition uses *. Strings are indexed from zero. f-strings embed variable values into output cleanly. Strings and numbers are different types and cannot be mixed with + directly.True or False. Comparison operators produce Boolean values. Boolean operators and, or, and not combine or modify them. = is assignment; == is comparison — never confuse them.print() displays output; input() receives a string from the user. Input must always be converted to the correct type before arithmetic. Type mismatches cause TypeErrors.int(), float(), str(), bool(). int() on a float truncates — it does not round. Falsy values include 0, 0.0, "", and None.+= and similar operators. Swapping two variables requires a temporary variable to preserve the original value.= operator. The right side evaluates first.True and False. Named after mathematician George Boole.+ operator to produce a longer string.f, in which expressions inside {} are evaluated and inserted.int(), float(), str(), or bool().+= pattern.Answer these questions to verify understanding before attempting practice problems.
= do? How is it different from the mathematical equals sign?7 // 3 produce? What does 7 % 3 produce?+ without conversion?= and ==?input() always return, regardless of what the user types?int(3.9) return? Does it round?Evaluate each expression and write the result.
5 + 3 * 2(5 + 3) * 210 // 310 % 32 ** 815 % 47 / 27 // 2True and FalseTrue or Falsenot True3 > 2 and 10 < 53 > 2 or 10 < 5not (5 == 5)len("computer")Construct a trace table for each program and write the output.
Program B1:
x = 4 y = 7 z = x + y x = z - x print(x) print(y) print(z)
Program B2:
a = 10 b = 3 a = a * b b = a // b print(a) print(b)
Program B3:
count = 0 total = 0 count += 1 total += 50 count += 1 total += 30 count += 1 total += 70 print(count) print(total)
Program B4:
word = "science" first_letter = word[0] length = len(word) print(first_letter) print(length) print(word[3])
For each question, define your variables clearly, write the program, and state what types you used and why.
C = (F - 32) * 5 / 9.Each program below contains a bug. Identify the error type (TypeError, ValueError, NameError, logic error), explain what is wrong, and write the corrected version.
score = 85 bonus = "10" final_score = score + bonus print(final_score)
What type error occurs? How do you fix it?
greeting = input("Name: ") message = "Hello, " + greeting length = len(message) print("Length: " + length)
The last line will cause an error. What is wrong? How do you fix it?
radius = float(input("Enter radius: ")) pi = 3.14159 area = pi * radius ^ 2 print(area)
Python does not use ^ for exponentiation. What operator should be used? What does ^ actually do in Python?
p = 5 q = 9 p = q q = p print(p, q)
The programmer intended to swap p and q. What does this code actually produce? Write the correct version using a temporary variable.
word = "hello" print(word[5])
The string "hello" has 5 characters. Why does word[5] cause an error? What is the correct index for the last character?
x = x + 1 is valid in programming but impossible in mathematics.7 / 2 and 7 // 2 in Python?3 + 4 * 2(3 + 4) * 217 % 5True and not Falselen("algorithm")int(7.9)bool("")x = 5 / y = x * 2 / x = y - 3 / print(x) / print(y)
total = 0 / total += 15 / total += 30 / total *= 2 / total -= 10 / print(total)
What is printed?
99, "99", 99.0, Falseage = input("Age: ") and then print(age + 1). What error occurs? Write the corrected version.int(5.9) and rounding 5.9 to the nearest integer?int), a health level (float), a username (str), and an active status (bool). For each attribute, explain why that type is appropriate and give one example operation the game might perform on it.// and %. Test with 100 days.These questions draw on Chapters 1–7.
"hello" is ultimately represented in binary in a computer's memory. What role does text encoding (such as ASCII or Unicode) play?Chapter 7 gave programs the ability to store values, compute expressions, and track state. But programs so far can only execute instructions from top to bottom in a fixed order. Every program in this chapter ran straight through without making any decisions or repeating anything.
Chapter 8 introduces control flow — the mechanisms that let a program take different paths depending on conditions, and repeat actions as many times as needed. If statements ask whether a Boolean expression is true and branch accordingly. While loops repeat a block of code as long as a condition holds. For loops repeat over a sequence of values. The Boolean values and comparison expressions from this chapter become the deciding factor in every branch and every loop. By the end of Chapter 8, programs will be able to make decisions, repeat work efficiently, and process information in flexible ways that begin to resemble the software people use every day.