Chapter 2: Working with Variables, Data Types, and Program Statements
In the previous chapter, you learned how to use operators to build expressions that perform arithmetic calculations. Now we're moving to a more powerful idea: storing and managing values using variables, organizing code with statements, and understanding how Python executes your programs.
This chapter is foundational. You'll learn how to create variables, work with modules to reuse code, use the print function effectively, and develop strategies for finding and fixing errors in your programs.
Variables
Creating and Understanding Variables
A variable is fundamentally a name that refers to a value. Think of it as a labeled container: the label is the variable name, and the container holds the value.
To create a variable, you write an assignment statement. Here's the basic structure:
n = 17
An assignment statement has three parts:
- The variable name on the left (in this case,
n) - The equals operator (
=) - An expression on the right (in this case, the integer
17)
The expression can be any kind of value. It might be an integer, a floating-point number (like 3.14159265358979), or a string (like 'And now for something completely different').
Here's what's important to understand: when you run an assignment statement, Python creates the variable and gives it a value, but the assignment statement itself produces no visible output. This is different from an expression, which displays a result when you evaluate it. After you create a variable, though, you can use it in other expressions to see its value.
Using Variables in Expressions and Functions
Once you've created a variable, you can use it in several ways:
- In arithmetic expressions: You can combine variables with operators. For example, if
n = 25, thenn + 25evaluates to50. - With the multiplication operator:
2 * pt(wherept = 3.14159265358979) evaluates to approximately6.283. - As arguments to functions:
round(pt)rounds the value to the nearest integer. Ifptis about3.14, thenround(pt)returns3. - In other function calls:
len(message)returns the length of a string stored in the variablemessage.
Assignment Statement: A statement that assigns a value to a variable, with the syntax
variable_name = expression. Assignment statements have no visible output but create or update the variable.
State Diagrams
Visualizing Variables and Their Values
On paper, a useful way to represent variables is with a state diagram. This is simply an arrow pointing from the variable name to its value:
n ———> 17
pi ———> 3.14159265358979
message ———> 'And now for something completely different'
We call this a state diagram because it shows the state of each variable—what value it currently holds. Think of a state diagram as a snapshot of your program's memory at a moment in time.
State diagrams are helpful tools throughout this book because they give us a concrete way to visualize how Python stores and manages variables. When variables change their values (which you'll learn about later), you can draw new state diagrams to show the updated state.
State Diagram: A graphical representation showing variable names with arrows pointing to their current values. State diagrams help visualize what data a program is storing and how it changes.
Variable Names
Rules and Conventions for Naming
Variable names can be as long as you want, and they can contain both letters and numbers—with one critical rule: a variable name cannot start with a number. Names like n, count, and radius_2 are all legal.
It's legal to use uppercase letters, but by convention, Python programmers use only lowercase for variable names. This keeps code consistent and readable. You can use the underscore character (_) as a connector between words in a multi-word name, like your_name or speed_of_unladen_swallow.
Keywords: Words You Cannot Use
Not every word is available for use as a variable name. Python reserves certain keywords—special words used to specify the structure of a program. If you try to use a keyword as a variable name, you'll get a syntax error.
Here's a complete list of Python's keywords:
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 don't need to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you'll immediately know.
Keyword: A special word used by Python to specify the structure of a program. Keywords cannot be used as variable names.
Syntax Errors from Invalid Names
Here are some real examples of what happens when you try to use illegal variable names:
million! = 1000000produces aSyntaxError: invalid syntaxbecause the!punctuation is not allowed.76trombones = 'big parade'produces aSyntaxError: invalid decimal literalbecause the name starts with a number.class = 'Self-Defence Against Fresh Fruit'produces aSyntaxError: invalid syntaxbecauseclassis a keyword.
The import Statement
Accessing Python Modules
To use some Python features, you need to import them first. A module is a file that contains Python code, including variable definitions and function definitions. Many useful modules come built-in with Python.
For example, to import the math module, you write:
import math
A module provides a collection of related variables and functions. The math module, for instance, contains a variable called pi that holds the value of the mathematical constant π:
math.pi
This evaluates to approximately 3.14159265358979.
Accessing Module Members with the Dot Operator
To use something inside a module, you use the dot operator (written as a period, .). You write the module name, then a dot, then the name of what you want from that module.
The math module also provides functions. The sqrt function computes square roots:
math.sqrt(25)
This returns 5.0. Similarly, math.pow(5, 2) raises 5 to the power of 2, returning 25.0.
Note: there are two ways to raise a number to a power—using the math.pow function or using the exponentiation operator **. The operator is more commonly used, but both work.
Module: A collection of variables and functions stored in a file. Modules allow you to reuse code and access pre-built functionality.
Dot Operator: The
.symbol used to access a function or variable inside a module. Syntax:module_name.item_name.
Expressions and Statements
Understanding the Difference
You've now encountered two different kinds of things you can write in Python: expressions and statements.
An expression is a combination of values, variables, and operators. It can be a single value like 5 or 'hello', or it can be more complex like 19 + n + round(math.pi) * 2. When you evaluate an expression, it produces a value.
A statement is a unit of code that has an effect but no value. For example, an assignment statement like n = 17 creates a variable and assigns it a value—it has an effect—but the statement itself does not produce or return a value. Similarly, an import statement like import math loads a module so you can use it, but it has no visible effect.
This distinction matters: expressions can be evaluated to get results, but statements perform actions.
Expression: A combination of values, variables, and operators that evaluates to produce a result.
Statement: A unit of code that performs an action or effect but does not produce a value. Assignment statements and import statements are examples.
The print Function
Displaying Values
When you evaluate an expression in the Python interpreter, the result is displayed automatically:
n + 1
This outputs 18 (assuming n = 17).
However, if you evaluate multiple expressions in sequence, only the last one is displayed:
n + 2
n + 3
This outputs only 20 (the result of the second expression). The first result is lost.
To display more than one value, use the print function:
print(n+2)
print(n+3)
This outputs:
19
20
Multiple Arguments and Different Data Types
The print function is very flexible. You can pass it multiple values separated by commas:
print('The value of pi is approximately')
print(math.pi)
This outputs:
The value of pi is approximately
3.14159265358979
You can also pass multiple arguments in a single print call:
print('The value of pi is approximately', math.pi)
This outputs:
The value of pi is approximately 3.14159265358979
Notice that the print function automatically puts a space between the values.
You can also pass a sequence of expressions separated by commas:
print('The value of pi is approximately', math.pi)
The print function works with integers, floats, and strings equally well.
Print Function: A built-in function used to display values on the screen. It can take multiple arguments separated by commas and automatically inserts spaces between them.
Arguments
Defining Arguments and Parameters
When you call a function, the expression inside the parentheses is called an argument. The technical term is specific: the argument is the value you provide, and the parameter is the variable inside the function that receives that value. For most purposes, though, people use these terms interchangeably.
Different functions take different numbers of arguments:
- Single argument:
int('101')converts the string'101'to the integer101. - Two arguments:
math.pow(5, 2)raises 5 to the power of 2, returning25.0. - Optional arguments: Some functions allow optional arguments. For example,
int('101', 2)interprets'101'as a number in base 2, so it returns5(since the binary number 101 equals 5 in base 10). - Many arguments: The
printfunction can take any number of arguments.
Error Handling with Arguments
If you provide the wrong number of arguments, Python raises a TypeError:
- Too many arguments:
float('123.0', 2)producesTypeError: float expected at most 1 argument, got 2. - Too few arguments:
math.pow(2)producesTypeError: pow expected 2 arguments, got 1. - Wrong type:
math.sqrt('123')producesTypeError: must be real number, not str.
These errors are helpful because they guide you to fix your code.
Argument: A value provided to a function when it is called. Each argument is assigned to a corresponding parameter inside the function.
Comments
Why Comments Matter
As programs grow larger and more complex, they become harder to read. Code is dense, and it's easy to lose track of why you wrote something or what it does.
Comments are notes you add to your program to explain what the code does and why. They start with the # symbol and extend to the end of the line:
# number of seconds in 42:42
seconds = 42 * 60 + 42
You can also put a comment at the end of a line:
miles = 10 / 1.61 # 10 kilometers in miles
Everything from the # to the end of the line is ignored—it has no effect on the execution of the program. Comments are most useful when they document non-obvious features of the code or explain why you did something a particular way, rather than restating what the code obviously does.
A comment like v = 8 # assign 8 to v is redundant with the code itself. But a comment like v = 8 # velocity in miles per hour adds useful information that is not in the code.
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read. This creates a trade-off: clarity requires finding a balance.
Comment: Text in a program that provides information about the code but has no effect on execution. Comments start with
#.
Debugging
Three Kinds of Errors
Errors in programming fall into three categories, and it's useful to distinguish among them:
Syntax Errors
A syntax error refers to the structure of a program and the rules about that structure. If there's a syntax error anywhere in your program, Python will not run it. Instead, it displays an error message immediately when you try to run the code. For example, trying to use the illegal variable name million! produces a syntax error.
Runtime Errors
If your program has no syntax errors, it can start running. However, if something goes wrong during execution, Python displays an error message and stops. This type of error is called a runtime error or an exception because it indicates that something exceptional has happened. For example, if you try to divide a string by an integer using '126' / 3, Python raises a TypeError: unsupported operand type(s) for /: 'str' and 'int'.
Semantic Errors
The third type of error is semantic, meaning "related to meaning." If there's a semantic error in your program, it runs without generating error messages, but it does not do what you intended. For example, suppose you want to compute the average of 1 and 3 but write 1 + 3 / 2. This evaluates to 2.5 (because division is performed before addition), not 2.0 (the correct average). There's no error message because the code is syntactically valid and runs successfully—it just computes the wrong thing.
Semantic errors are the hardest to find because they require you to work backward from the program's output, figure out what went wrong, and track down the source. This is why testing your code with multiple inputs is important.
Syntax Error: An error in the structure of a program. Python detects these immediately and refuses to run the program.
Runtime Error (Exception): An error that occurs while a program is running, causing Python to display an error message and stop execution.
Semantic Error: An error where a program runs without error messages but does not do what was intended.
Summary
In this chapter, you learned the fundamentals of working with data and code structure in Python:
- Variables are names that store values, created using assignment statements.
- State diagrams visually represent variables and their current values.
- Variable naming follows specific rules: start with a letter or underscore, avoid keywords, and use lowercase with underscores between words by convention.
- Modules provide reusable code; you access module members using the dot operator.
- Expressions evaluate to produce values, while statements perform actions.
- The print function displays one or more values on the screen.
- Arguments are values you provide to functions when calling them.
- Comments document your code and explain your reasoning.
- Debugging involves identifying and fixing three types of errors: syntax, runtime, and semantic.
Understanding these concepts deeply will make you a better programmer. Variables and statements are the building blocks of every Python program, and the debugging skills you're developing now will serve you throughout your coding career.
📝 Chapter Recap: Variables store values using assignment statements, modules provide reusable code accessed via the dot operator, and Python distinguishes between expressions (which produce values), statements (which perform actions), and three types of errors (syntax, runtime, and semantic). The print function displays output, arguments customize function behavior, and comments document your code. Together, these tools form the foundation for writing clear, effective Python programs.