Chapter 2: Variables, Statements, and Errors in Python#
This chapter builds on the idea of expressions from Chapter 1 and introduces one of the most important tools in any programming language: variables. You'll also learn how to bring in extra Python tools using the import statement, how to display output with print, and how to understand the three types of errors that can trip you up as you write code.
Variables#
What is a Variable?#
At its most basic level, a variable is a name that points to a value stored in the computer's memory. Think of it like a labelled box — you write a name on the outside, put something inside, and from that point on you can refer to the contents just by using the label.
To create a variable, you write an assignment statement. An assignment statement has three parts:
- The variable name (on the left)
- The equals sign
=(the assignment operator) - An expression whose value will be stored (on the right)
Here are three examples, each storing a different type of value:
n = 17 # stores an integer
pi = 3.141592653589793 # stores a floating-point number
message = 'And now for something completely different' # stores a stringOne thing that surprises beginners: when you run an assignment statement, Python does its work silently — you see no output. But once the variable exists, you can use it anywhere you would use a value directly. You can plug it into arithmetic, pass it to a function, or just type its name to display its current value.
n + 25 # gives 42
round(pi) # gives 3
len(message) # gives 42State Diagrams#
A useful way to picture variables on paper is to draw a state diagram: write each variable name and draw an arrow pointing to its current value. For example:
n --> 17
pi --> 3.141592653589793
message --> 'And now for something completely different'State diagrams show the "state of mind" of your program at a particular moment — what every variable currently holds. You'll find them helpful when tracing through a program step by step to understand what's happening.
Variable Names: The Rules#
Variable names can be almost anything you like, but there are a few hard rules Python enforces:
- Names can contain letters and digits, but cannot start with a digit. So
speed2is fine, but2speedis not. - The only punctuation allowed is the underscore
_. It's commonly used to join words:air_speed,your_name. - By convention, use all lowercase letters for variable names.
- Variable names cannot be keywords — special reserved words that Python uses for its own grammar.
If you break any of these rules, Python raises a syntax error and refuses to run your program at all.
Python Keywords#
A keyword is a word that Python has reserved for its own use — things like if, for, while, def, and so on. You cannot use these as variable names. Here is the full list:
| False | await | else | import | pass |
| None | break | except | in | raise |
| True | class | finally | is | return |
| and | continue | for | lambda | try |
| as | def | from | nonlocal | while |
| assert | del | global | not | with |
| async | elif | if | or | yield |
You do not need to memorise this table. In most code editors, keywords are automatically displayed in a different colour, so you'll spot them right away.
Variable: A name that refers to a value stored in memory.
Assignment Statement: A line of code that creates a variable and stores a value in it, using the form
name = expression.
Keyword: A reserved word that Python uses for its own grammar and that cannot be used as a variable name.
State Diagram: A visual representation of variables and the values they currently hold, drawn as names with arrows pointing to their values.
📝 Section Recap: Variables are named containers for values. You create them with assignment statements. Names must follow certain rules — no starting digit, only underscores as punctuation, and no keywords. State diagrams are a handy tool for visualising what a program's variables currently hold.
The import Statement#
Modules and Why We Need Them#
Python comes with a large library of extra tools that are not loaded by default — they live in separate files called modules. A module is a collection of variables and functions that extend what Python can do. To access a module's contents, you use the import statement.
import mathAfter this one line, everything inside the math module becomes available to you. The math module contains a variable called pi that holds the value of the mathematical constant
Using the Dot Operator#
To reach inside a module and use one of its variables or functions, you use the dot operator (.): write the module name, then a dot, then the name of what you want.
math.pi # the value of pi: 3.141592653589793
math.sqrt(25) # square root of 25: gives 5.0
math.pow(5, 2) # 5 raised to the power 2: gives 25.0Think of the dot like a possessive: math.pi means "the pi that belongs to math."
A useful note: you can raise a number to a power using either math.pow(base, exponent) or the built-in exponentiation operator **. Both produce the same result, but the ** operator is more commonly used in practice.
Module: A file containing Python code — variables, functions, and sometimes other statements — that can be imported and used in your own program.
Import Statement: A statement that loads a module so its contents become available, written as
import module_name.
Dot Operator: The
.symbol used to access a variable or function that belongs to a module, written asmodule_name.item_name.
📝 Section Recap: Modules are bundles of extra Python tools. You load them with
import, and you access their contents with the dot operator. Themathmodule is a prime example, giving you constants likepiand functions likesqrtandpow.
Expressions and Statements#
What is an Expression?#
You've already been working with expressions without necessarily using that word. An expression is any piece of code that produces a value when Python evaluates it. That could be:
- A bare value:
42,3.14,'hello' - An arithmetic calculation:
2 + 3 * 4 - A variable name:
n - A function call:
round(math.pi) - Any combination of the above:
19 + n + round(math.pi) * 2
When Python works out what an expression equals, that process is called evaluation.
What is a Statement?#
A statement, by contrast, is a unit of code that does something but does not itself produce a value you can use. Assignment statements and import statements are both examples:
n = 17 # assignment statement — creates a variable
import math # import statement — loads a moduleNeither of these lines produces a result you can see or pass to another expression. Running a statement is called execution.
A helpful way to keep these straight: if you can use it on the right side of an equals sign, it's an expression. If it performs an action but gives you nothing back, it's a statement.
Expression: Code that evaluates to a value — a number, string, variable, function call, or any combination.
Statement: Code that performs an action but has no value itself. Assignment and import are common examples.
Evaluation: The process Python uses to compute the value of an expression.
Execution: The process of running a statement so that its action takes place.
📝 Section Recap: Expressions produce values; statements perform actions. Evaluation computes an expression's result; execution carries out a statement's effect. Understanding this distinction helps you predict what Python will and won't display when you run code.
The print Function#
Why print Exists#
When you type an expression directly into an interactive Python session, its value is shown. But in a script — or when you have multiple expressions to display — you need the print function.
The key limitation without print: if you write several expressions one after another, Python only displays the last one. The ones before it are evaluated and discarded.
print solves this by explicitly sending output to the screen. You can call it once per line to display as many values as you need:
print(n + 2) # displays 19
print(n + 3) # displays 20Printing Multiple Values at Once#
You can also pass several values to print in a single call by separating them with commas. Python will display them all on one line, automatically placing a space between each one:
print('The value of pi is approximately', math.pi)
# output: The value of pi is approximately 3.141592653589793This is a handy shortcut — you don't need to build a single combined string yourself.
📝 Section Recap: The
Arguments#
What is an Argument?#
When you call a function, the values you put inside the parentheses are called arguments. The function receives those values and uses them to do its work.
Different functions expect different numbers of arguments:
| Function | Number of arguments | Example |
|---|---|---|
int('101') |
1 required | Converts string to integer |
math.pow(5, 2) |
2 required | Computes |
int('101', 2) |
1 required + 1 optional | Converts binary string to int |
round(math.pi, 3) |
1 required + 1 optional | Rounds to 3 decimal places |
print(...) |
Any number | Displays all values given |
Optional Arguments#
Some functions accept optional arguments — extra inputs that have a default behaviour if you leave them out. For instance, round(x) rounds to the nearest whole number by default. But round(x, 2) rounds to 2 decimal places. The second argument is optional; including it just gives you more control.
TypeError: When Arguments Go Wrong#
Python checks that you're passing the right number and type of arguments. If you get it wrong, you'll see a TypeError. This can happen three ways:
- Too many arguments:
float('123.0', 2)—floatonly accepts one argument. - Too few arguments:
math.pow(2)—powneeds two. - Wrong type:
math.sqrt('123')—sqrtneeds a number, not a string.
These errors can feel frustrating when you're learning, but they're actually Python being helpful — they catch mistakes early so you can fix them before they cause bigger problems.
Argument: A value passed to a function when you call it. Each argument fills one of the function's expected inputs.
📝 Section Recap: Arguments are the values you feed to a function. Some functions require a fixed number; others accept optional extras. Python will raise a TypeError if you provide the wrong number or the wrong type of arguments — this is a feature, not a bug.
Comments#
What is a Comment?#
As programs grow larger, the code alone can become hard to follow. Comments are notes you write in plain English inside your code to explain what's going on. Python ignores everything on a line after the # symbol — it has no effect on how the program runs.
# number of seconds in 42 minutes and 42 seconds
seconds = 42 * 60 + 42You can also add a comment at the end of a code line:
miles = 10 / 1.61 # 10 kilometers converted to milesWhat Makes a Good Comment?#
The golden rule: don't explain what the code does (a reader can usually work that out); explain why it does it, or what the number or value represents.
A redundant comment that adds nothing:
v = 8 # assign 8 to vA useful comment that adds meaning:
v = 8 # velocity in miles per hourThere's also a useful trade-off to keep in mind: a well-chosen, descriptive variable name (like velocity_mph instead of v) can make comments unnecessary in the first place. But very long names can make expressions hard to read, so you have to use your judgement.
Comment: Text added to a program with
#to explain the code in plain language. Python ignores it completely during execution.
📝 Section Recap: Comments let you leave human-readable notes inside your code. They are ignored by Python but invaluable for readers (including your future self). The best comments explain intent and meaning, not what is already obvious from the code.
Debugging#
The Three Types of Errors#
When something goes wrong in a program, the problem always falls into one of three categories. Knowing which type you're dealing with tells you how to find it and fix it.
Syntax Errors#
A syntax error means your code breaks Python's grammatical rules — it's the equivalent of a sentence that is so badly formed the reader cannot parse it at all. Python catches these before running anything and immediately displays an error message pointing to the problem line.
Common causes: using a keyword as a variable name, starting a name with a digit, or using illegal punctuation like ! in a name.
Syntax Error: An error caused by code that violates Python's grammatical rules. Python detects it immediately and will not run the program.
Runtime Errors#
A runtime error (also called an exception) occurs after your program has started running. The code was grammatically valid, but something went wrong during execution — for example, using the division operator / on a string, or passing the wrong type to a function.
When a runtime error occurs, Python stops the program and prints an error message describing what happened.
Runtime Error: An error detected while the program is running that causes it to stop and display an error message. Also called an exception.
Exception: Another name for a runtime error — something unexpected that interrupted the program's normal flow.
Semantic Errors#
A semantic error is the trickiest type. The code runs to completion without any error message, but the result is wrong. The program does something different from what you intended.
A classic example: wanting the average of 1 and 3, but writing 1 + 3 / 2 instead of (1 + 3) / 2. Python evaluates this as
Fixing semantic errors requires detective work: you look at the output, trace back through the logic, and figure out where the program's reasoning diverged from your intention.
Semantic Error: An error where the program runs without crashing but produces the wrong result because the code does not do what was intended.
| Error Type | When detected | Produces error message? | Example |
|---|---|---|---|
| Syntax | Before running | Yes, immediately | million! = 1000000 |
| Runtime | During execution | Yes, when it occurs | '126' / 3 |
| Semantic | After running | No | 1 + 3 / 2 instead of (1+3)/2 |
📝 Section Recap: There are three types of programming errors. Syntax errors are caught before the program runs — your grammar is broken. Runtime errors (exceptions) happen during execution and stop the program. Semantic errors are the sneakiest: the program runs fine, but gives the wrong answer because the logic is flawed. Learning to distinguish between these three will make you a much faster debugger.
Key Term Reference#
Below is a consolidated glossary of all the important terms introduced in this chapter.
| Term | Meaning |
|---|---|
| Variable | A name that refers to a value |
| Assignment statement | A statement that stores a value in a variable using = |
| State diagram | A diagram showing variables and the values they currently hold |
| Keyword | A reserved word Python uses for its own grammar; cannot be a variable name |
| Module | A file of Python code that can be imported to add extra features |
| Import statement | A statement that loads a module with import module_name |
| Dot operator | . used to access items inside a module, as in math.pi |
| Statement | Code that performs an action but produces no value |
| Expression | Code that evaluates to a value |
| Evaluation | Computing the value of an expression |
| Execution | Carrying out the action of a statement |
| Argument | A value passed to a function when calling it |
| Comment | An explanatory note in code, starting with #, ignored by Python |
| Runtime error / Exception | An error detected during execution that stops the program |
| Semantic error | An error where the program runs but produces the wrong result |
| Syntax error | An error caused by invalid code structure, caught before running |