The smallest building blocks of every Python program — how information is stored, named, computed, and traced
Every program works with information. Before a program can print a result, make a decision, repeat a task, or read a file, it needs to store and manipulate values. This chapter introduces the smallest building blocks of Python programs: values, variables, assignment, and expressions. By the end of this chapter, you will be able to read simple Python programs, trace how values change as each line runs, and write programs that compute and store results.
The concepts in this chapter are not complicated on their own — but they are fundamental. Variables, expressions, and assignment appear in every Python program you will ever read or write. Getting a precise, accurate understanding of how they work now will make everything that follows much easier.
Chapter 2 taught you how to run Python programs. Chapter 3 teaches you what those programs are made of. Numbers, text, True/False values, names, calculations, and the rules Python uses to evaluate them — these are the vocabulary of the language. This chapter builds that vocabulary carefully before programs grow into conditionals, loops, and functions.
By the end of this chapter, you should be able to:
= operator does.type() function; values versus variable names=; how Python evaluates the right side first; reassignment; why variables do not have permanent typesint() and float() conversion; when Python produces floats automatically; / versus //%; integer and float mixing+; repetition with *; a preview of Chapter 16True and False; Booleans from comparison expressions; storing Booleans in variables; preview of decision-making in Chapter 6A value is a piece of information that a program works with. When you run a Python program, almost everything the program does involves values. The number 42 is a value. The text "hello" is a value. The result of multiplying 6 by 7 is a value.
Python recognizes many kinds of values. For now, the four most important ones are:
0, 17, -5, 1000. Python integers can be arbitrarily large.3.14, 0.5, -2.7. Named for the floating-point representation used internally."Python", 'hello', "42". A string is a sequence of characters — letters, digits, spaces, punctuation, or any combination.True and False. Booleans represent yes/no, on/off, and other two-state conditions. They are the foundation of all decision-making in Python programs.Each value belongs to a type. The type of a value tells Python what kind of information it is and what operations make sense for it. You can ask Python to tell you the type of any value using the built-in type() function:
type(42)
type(3.14)
type("hello")
type(True)
In the Python interactive shell, these produce:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Python accepts both single quotes ('hello') and double quotes ("hello") for strings — either works. Throughout this textbook, double quotes are used by default. The only rule is that the opening and closing quote must match.
Values are not the same as variable names. The value 42 is the number forty-two. A variable named score might hold the value 42, but the name and the value are different things. Section 3.2 explains this distinction carefully.
A variable is a name that refers to a value stored in the computer's memory. Variables let programs remember information, reuse it later, and change it when necessary.
In Python, you create a variable and give it a value using an assignment statement. The general form is:
variable_name = expression
The = sign in Python is the assignment operator. It does not mean "equals" the way it does in mathematics. It means: evaluate the right side, then store the result under the name on the left. The direction of flow is always right-to-left.
Here are four assignment statements, one for each value type:
score = 95
price = 4.99
greeting = "Hello, world!"
is_valid = True
After these lines run, Python has four variables in memory. You can use any variable anywhere you would use its value directly. If score holds 95, then score + 5 produces 100.
A variable does not hold its value forever. You can assign a new value to it at any time:
score = 95
score = 80
score = score + 5
After the first line, score is 95. After the second line, score is 80. After the third line, score is 85 — because Python evaluates the right side first (80 + 5 = 85) and then stores 85 back into score.
score = score + 5score + 5. The current value of score is 80, so this becomes 80 + 5.80 + 5, producing 85.85 into the variable named score. The old value 80 is gone.score now holds 85. Python was not confused by score appearing on both sides because it always finishes evaluating the right side before performing the assignment.Beginners sometimes read score = score + 5 as a mathematical equation and think "that's impossible — score can't equal itself plus five." In Python, this is not an equation. It is a two-step instruction: compute score + 5, then store the result back into score. The old value is replaced.
Python has rules for what variable names are allowed. Good programmers follow additional conventions that make code easier to read and maintain.
| Rule | Detail |
|---|---|
| Start with a letter or underscore | The first character must be a letter (a–z, A–Z) or an underscore (_). It cannot be a digit. |
| Letters, digits, underscores only | After the first character, the name may contain letters, digits (0–9), and underscores. No spaces, hyphens, or other punctuation. |
| No Python keywords | Reserved words such as if, for, while, def, True, False, None, and, or, not, return, class, and import cannot be used as variable names. |
score total_price item_count first_name x value1 _internal1score — starts with a digittotal-price — hyphens are not allowedfirst name — spaces are not allowedif — reserved keyword; produces a SyntaxErrorPython's community convention is snake_case: all lowercase letters, with underscores between words. This is not enforced by the language, but it is expected by other Python programmers:
student_name = "Alex"
high_score = 100
average_temperature = 72.5
Avoid short, cryptic names like x, n, or tmp unless the meaning is obvious from context. Use names that describe what the variable holds, not how it is computed:
# Clear — the name tells you what it is
total_cost = price * quantity
# Unclear — the name tells you nothing
tc = p * q
Python treats uppercase and lowercase letters as different characters. Score, score, and SCORE are three distinct variable names. By convention, ordinary variable names use all lowercase with underscores. Names in ALL_CAPS are reserved for constants — values meant never to change.
Taking time to name variables well is not a cosmetic concern. Descriptive names reduce errors, make programs easier to read, and help other programmers — including your future self — understand your code without needing to trace it line by line.
Python has two main numeric types: integers and floats. Knowing which type to use — and when Python will produce one or the other — prevents a category of errors that trips up many beginners.
Integers represent whole numbers without a fractional part. They can be positive, negative, or zero:
students = 30
temperature = -5
year = 2024
zero = 0
Python integers can be arbitrarily large — there is no upper limit for ordinary programs.
Floats represent numbers with a decimal point:
price = 19.99
weight = 0.75
pi = 3.14159
negative_float = -2.5
Try 0.1 + 0.2 in the Python shell. Python may display 0.30000000000000004. This is not a bug — it is a consequence of how all computers store decimal numbers in binary. For most programs at this stage, this will not cause problems. But it is worth knowing that 0.1 + 0.2 does not produce exactly 0.3 in Python.
Python provides functions to convert between integer and float types:
int(3.9) # produces 3 — truncates (drops) the decimal, does NOT round
int(3.1) # produces 3
float(7) # produces 7.0
Whenever you use the / operator, Python always produces a float result, even when both values are integers:
10 / 2 # produces 5.0, not 5
7 / 2 # produces 3.5
If you need a whole-number result, use integer division with //:
10 // 2 # produces 5
7 // 2 # produces 3 (the remainder 1 is discarded)
This distinction matters whenever your program counts things, indexes a list, or requires a whole-number result for further calculation.
Python provides seven arithmetic operators for working with numeric values.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division (always float) | 9 / 2 | 4.5 |
// | Integer division (truncates) | 9 // 2 | 4 |
% | Remainder (modulo) | 9 % 2 | 1 |
** | Exponentiation | 2 ** 8 | 256 |
The % operator is less familiar than the others, but it is genuinely useful. 9 % 2 produces 1 because 9 = 4 × 2 + 1 — four goes into nine twice, with a remainder of one.
number % 2 == 0 is True for even numbers, False for odd ones. This is one of the most common uses of %.n % 10 extracts the last digit of any integer. 137 % 10 produces 7.150 // 60 gives 2 hours; 150 % 60 gives 30 remaining minutes.The ** operator raises the left value to the power of the right value:
2 ** 10 # produces 1024
3 ** 3 # produces 27
9 ** 0.5 # produces 3.0 (the square root of 9)
When you combine an integer and a float in an arithmetic expression, Python produces a float result:
3 + 0.5 # produces 3.5
10 * 2.0 # produces 20.0
An expression is a combination of values, variables, and operators that Python evaluates to produce a single result. Every expression has a value.
Here are examples of expressions — each one produces a value when Python evaluates it:
5 + 3
score * 2
price - discount
(length + width) * 2
temperature / 5 + 32
When Python encounters an expression, it evaluates it — it computes the result. The result can then be stored in a variable, printed, used in another expression, or returned from a function.
Variables can appear anywhere a value can appear:
width = 10
height = 5
area = width * height
perimeter = 2 * (width + height)
Python reads the values stored in width and height, performs the calculations, and stores the results in area and perimeter.
Some Python built-in functions return values that can be used inside expressions:
largest = max(17, 42, 8) # 42
smallest = min(17, 42, 8) # 8
absolute = abs(-15) # 15
rounded = round(3.7) # 4
An assignment statement like score = 95 is not an expression — it does not produce a value. It performs an action: it stores a value into a name. This distinction matters more when you begin working with conditionals and function return values in later chapters.
When an expression contains more than one operator, Python needs rules to decide which operation to perform first. These rules are called operator precedence.
Python follows the same order taught in mathematics:
| Priority | Operator(s) | Description |
|---|---|---|
| 1 (highest) | ( ) | Parentheses — always evaluated first |
| 2 | ** | Exponentiation |
| 3 | - (unary) | Negation of a single value, as in -5 |
| 4 | * / // % | Multiplication, division, integer division, remainder — evaluated left to right |
| 5 (lowest) | + - | Addition and subtraction — evaluated left to right |
2 + 3 * 4Multiplication first: 3 * 4 = 12, then 2 + 12 = 14. Result: 14, not 20.(2 + 3) * 4Parentheses first: 2 + 3 = 5, then 5 * 4 = 20. Result: 20.10 - 4 / 2Division first: 4 / 2 = 2.0, then 10 - 2.0 = 8.0. Result: 8.0.2 ** 3 + 1Exponentiation first: 2 ** 3 = 8, then 8 + 1 = 9. Result: 9.20 - 5 - 3Equal precedence — left to right: (20 - 5) - 3 = 15 - 3 = 12. Result: 12, not 18.Even if you know the rules, parentheses that clarify your intent make code easier to read and less prone to errors.
Less clear: result = a + b * c - d / e
Clearer: result = a + (b * c) - (d / e)
Good programmers use parentheses not just when required, but whenever they make the expression's meaning clearer to a reader.
A string is a sequence of characters enclosed in quotation marks. Strings represent text: names, messages, file paths, labels, input from users, and any information expressed as written characters rather than as numbers.
first_name = "Morgan"
city = "Chicago"
message = "Your score is excellent."
empty = ""
The last example, "", is the empty string — a string with no characters. It is a valid string value.
Even if a string looks like a number, Python treats it as text:
x = "42" # a string — the characters '4' and '2'
y = 42 # an integer — the number forty-two
Trying to add x + y (a string and an integer) produces a TypeError. Python does not automatically convert between types. The distinction between "42" and 42 is fundamental. Chapter 4 explains how to convert between them using int() and str().
You can join two strings together using +. This is called concatenation:
first = "Hello"
second = "world"
combined = first + " " + second # "Hello world"
Notice the space in the middle — Python does not add spaces automatically. You must include them explicitly in the string.
You can repeat a string using *:
line = "-" * 20 # "--------------------"
Strings have many capabilities beyond what this chapter covers: indexing individual characters, slicing portions, searching for substrings, and dozens of useful methods. Chapter 16 covers strings in depth. For now, the key ideas are: strings hold text, they are created with quotation marks, they are not numbers, and you can join them with +.
A Boolean is a value that is either True or False. Booleans are named after the mathematician George Boole, who developed the algebra of logical reasoning.
In Python, the two Boolean values are written with capital first letters. They are not strings — do not write them in quotation marks:
True # the Boolean value True
False # the Boolean value False
"True" # a string — the word "True" stored as text (different thing)
Boolean values are often the result of comparing two values. Comparison expressions produce either True or False:
10 > 5 # True
10 < 5 # False
10 == 10 # True
10 == 5 # False
10 != 5 # True (not equal)
You can store Boolean values in variables, just like any other type:
is_logged_in = True
has_error = False
age_is_valid = age >= 18
Booleans are the language programs use to make decisions. Every if statement, every loop condition, and every logical check in a Python program ultimately depends on a Boolean value. Chapter 5 covers Boolean logic in full detail. For now, it is enough to know that Booleans exist, they can be stored in variables, and they are the result of comparisons.
A small preview: after temperature = 30 and is_hot = temperature > 25, the variable is_hot holds True. In Chapter 6, you will use values like this to control which parts of a program run.
Tracing means following a program's execution step by step and recording the value of each variable at each point. Tracing is one of the most important skills in programming. When a program produces a wrong result, tracing reveals exactly where the values go wrong.
A tracing table is a systematic way to record how variables change as lines execute. The columns are the variable names. The rows represent lines of code. Each cell records the value of the variable after that line runs.
Here is the program to trace:
x = 10
y = 3
z = x + y
x = x * 2
z = z + x
Build the table one line at a time. Write a dash for variables that do not exist yet.
| Line | Code | x | y | z | Note |
|---|---|---|---|---|---|
| 1 | x = 10 | 10 | — | — | x created; y and z do not exist yet |
| 2 | y = 3 | 10 | 3 | — | y created |
| 3 | z = x + y | 10 | 3 | 13 | 10 + 3 = 13; stored in z |
| 4 | x = x * 2 | 20 | 3 | 13 | 10 * 2 = 20; old value 10 is gone |
| 5 | z = z + x | 20 | 3 | 33 | x is now 20 (not 10): 13 + 20 = 33 |
Line 4 changed x to 20. Line 5 used that updated value. If you had mistakenly carried x = 10 into Line 5, you would have computed 13 + 10 = 23 — wrong. This is exactly the kind of error that tracing catches before it becomes a bug.
After all five lines: x = 20, y = 3, z = 33.
first = "Alex"
last = "Kim"
full_name = first + " " + last
greeting = "Hello, " + full_name + "!"
| Line | Code | first | last | full_name | greeting |
|---|---|---|---|---|---|
| 1 | first = "Alex" | "Alex" | — | — | — |
| 2 | last = "Kim" | "Alex" | "Kim" | — | — |
| 3 | full_name = first + " " + last | "Alex" | "Kim" | "Alex Kim" | — |
| 4 | greeting = "Hello, " + full_name + "!" | "Alex" | "Kim" | "Alex Kim" | "Hello, Alex Kim!" |
Go through the program one line at a time, in order. Evaluate the right side before performing any assignment. Update the table after each line. Do not skip ahead. Tracing is not guessing — it is systematic, deliberate reading. Programmers at every level use tracing to understand unfamiliar code and hunt down bugs.
int, float, str, and bool. Each type determines what operations are valid. The type() function reports a value's type.= to evaluate the right side first and store the result under the left-side name. Variables can be reassigned at any time; the old value is replaced./ operator always produces a float. The // operator performs integer division. Floats have minor imprecision due to binary representation. Use int() and float() to convert between types.+, -, *, /, //, %, and **. The remainder operator % is useful for detecting even/odd, extracting digits, and time conversions. Mixing integers and floats produces floats."42" and 42 are different. Strings join with + (concatenation) and repeat with *. Mixing strings and numbers with + produces a TypeError.True and False. They are the result of comparison expressions and will become the foundation of all decision-making starting in Chapter 5.= symbol in Python. Evaluates the right side and stores the result in the variable named on the left. Not the same as mathematical equality.variable_name = expression.True or False. The Python type is bool. Used for all decision-making in programs.+ operator. Does not add spaces automatically.float. Stored as floating-point binary internally, which can cause minor imprecision.int. Can be arbitrarily large in Python.// operator. Always produces an integer result.if, for, True, or def. Cannot be used as a variable name.% operator, which produces the remainder after integer division. 9 % 2 produces 1.student_name, total_cost.str. A sequence of characters — not a number, even if it looks like one.int, float, str, or bool — which determines what operations are valid for that value.Compute the result of each expression by hand. Do not use Python yet — work it out first, then verify your answer in the shell.
8 + 3 * 2(8 + 3) * 215 / 415 // 415 % 42 ** 5100 - 3 * 4 + 2(100 - 3) * (4 + 2)17 % 55 ** 2 - 4 * 2 + 110 / 4 + 10 // 4"Hello" + " " + "Python""*" * 8type(3.0)type(3)For each program, build a complete tracing table. Record the value of each variable after each line executes. Write a dash if the variable does not yet exist.
a = 5
b = 12
c = a + b
a = a * 3
c = c - a
price = 8.50
quantity = 4
total = price * quantity
discount = 5.00
total = total - discount
x = 100
x = x // 3
remainder = 100 % 3
x = x + remainder
first = "Kim"
last = "Jordan"
full = last + ", " + first
label = "Name: " + full
base = 2
result = base ** 0
result = result + base ** 1
result = result + base ** 2
result = result + base ** 3
What is the final value of result? Can you see a pattern? What would the next step produce?Predict exactly what Python will display. Then run each program to check your prediction.
x = 7
y = x * 3
print(y)
name = "Taylor"
print("Hello, " + name + "!")
a = 10
b = 3
print(a // b)
print(a % b)
total = 0
total = total + 10
total = total + 25
total = total + 7
print(total)
x = 5
x = x + x
x = x * x
print(x)
n = 13
print(n % 2)
print(n // 2)
print(n / 2)
word = "Python"
print(word + "!")
print(word * 3)
a = 4
b = 7
temp = a
a = b
b = temp
print(a)
print(b)
What does this program do? Describe it in one sentence after predicting the output.Each code block contains one or more errors. Identify the error, explain what is wrong, and write a corrected version.
1score = 95total cost = price * quantityx = 10
y = 3
print(x + "3")
if = 42result = (5 + 3price = "9.99"
total = price * 3
True = 1balance = 100
Balance = balance + 50
print(balance)
This program runs without an error, but it probably does not do what the programmer intended. What is the problem? What should the programmer write instead?For each task, write a complete Python program. Run it to verify it works correctly.
area and perimeter and print both with descriptive labels.number and then uses two separate print() statements to display the result of number % 2 and number // 2. (Do not use an if statement — just print the values.)F = C × 9/5 + 32. Write a program that stores a Celsius temperature of 25 in a variable and computes the Fahrenheit equivalent.balance = 500, then subtracts three expenses of 80, 45, and 120 one at a time (using three separate assignment statements), and prints the final balance.* repetition operator, build and print this label — store the stars and message in separate variables before combining them:
***** Welcome to Python *****
speed, then computes how long a 360-mile trip would take at that speed in a variable named trip_hours. Print both.Answer each question in one to three sentences.
= do in Python? How does it differ from the = sign in mathematics?x = x + 1. Why is this not a contradiction?/ and // in Python? Give an example where they produce different results.% operator compute? Give one practical use for the remainder operator beyond the examples in this chapter."42" not the same as the integer 42? What would happen if you tried to add them together in Python?20 - 5 - 3? What result does this expression produce, and why?int, float, str, and bool.type() to check what type a value belongs to."42" and the integer 42 are different."" is and that it is a valid value.= means in Python.x = x + 1 works and why it is not a contradiction.+, -, *, /, //, %, **./ always produces a float, even with two integers.% computes and give a practical use for it.+ and repeat them with *.+ causes a TypeError.True and False are Boolean values, not strings.x = x + 1 is impossible — a number can't equal itself plus one."= is not a mathematical equation — it is an assignment instruction. Python evaluates the right side first (the current value of x plus one), then stores the result back into x. The old value is replaced. This pattern is one of the most common in all of programming."42" and 42 are the same thing — they're both forty-two.""42" is a string containing the characters 4 and 2. 42 is an integer. You cannot add them together ("42" + 1 produces a TypeError), and Python will not automatically convert one to the other. Always be aware of which type you are working with.= and math's = mean the same thing."x = 5 is a statement of equality — both sides are the same. In Python, x = 5 is an instruction to store the value 5 in the variable named x. Python's = always flows right-to-left and always represents an action, not a relationship.10 / 2 produces 5."10 / 2 produces 5.0 — a float, not an integer. The / operator always returns a float. If you need the integer 5, use 10 // 2 instead.Chapter 3 introduced values, variables, and expressions — the raw material of Python programs. But so far, programs have not been interactive: they do not ask questions, respond to the user, or display formatted results.
Chapter 4 introduces how Python programs communicate with the person running them. You will learn the print() function in depth, including how to display text and numbers together cleanly. You will learn the input() function, which lets a program receive typed text from the user. You will learn type conversion — how to turn a string from input() into a number you can calculate with. And you will learn f-strings, Python's clean and readable way to build formatted output. By the end of Chapter 4, you will be able to write interactive programs that ask for information, perform calculations, and display results in a clear, readable format.