Chapter 2 · pp. 31–38
Variables, Expressions and Statements
One of the most useful things a programming language lets you do is store values under names and then work with them. This chapter explains how to create variables, how to name them correctly, and how Python builds values from expressions. It also covers working with strings, writing comments, and the three kinds of errors you will meet when debugging.
Variables and assignment
A variable is a name that refers to a value. You create one with an assignment statement, which uses = to attach a name to a value (p. 31). For example:
message = 'hello'
n = 17
pi = 3.14159
The first line links the name message to a string. The second links n to the integer 17. The third links pi to a decimal number (p. 31).
A state diagram is a drawing of this idea. You write each variable's name and draw an arrow from it to the value it refers to. The diagram shows the "state" of every variable at one moment (p. 31).
Choosing legal variable names
Programmers pick names that are meaningful, so the name itself tells you what the variable is for (pp. 31–32). Python has a few rules for names:
- A name can be as long as you like.
- It can contain letters, digits, and underscores.
- It cannot begin with a digit.
- It cannot contain symbols such as
@.
The underscore is handy for names with several words, such as your_name (p. 32). Uppercase letters are allowed, but the convention is to use lowercase for variable names (p. 32).
Breaking a rule gives a syntax error. 76trombones fails because it starts with a digit. more@ fails because of the @ (p. 32).
Keywords
A keyword is a reserved word. Python uses keywords to understand the structure of a program, so you cannot use them as variable names. Examples are class, if, def, while, and return (p. 32). A line like class = 'Zymurgy' looks fine but causes a syntax error, because class is reserved. You do not need to memorize the list. Most editors show keywords in a different color, which warns you when you type one (p. 32).
Expressions and statements
An expression combines values, variables, and operators. Python evaluates it, meaning it finds its value. A single value, such as 42, counts as an expression. So does a single variable, such as n. If n is 17, then n + 25 evaluates to 42 (p. 32).
A statement is a unit of code that does something, such as creating a variable or displaying output. Python executes a statement, meaning it carries out the instruction. n = 17 is a statement that creates a variable. print(n) is a statement that displays a value (pp. 32–33). In general, a statement has no value of its own, while an expression always does (p. 33).
Interactive mode and script mode
In interactive mode, you type code directly at the interpreter prompt. This suits testing a few lines. In script mode, you save code in a file called a script, usually named with a .py ending, and run the whole file. Scripts work better for longer programs (p. 33). A common habit is to test small pieces interactively before putting them into a script (p. 33).
The two modes treat a lone expression differently, and this surprises many beginners (p. 33):
- Interactive: typing
miles * 1.61 at the prompt (with miles = 26.2) shows 42.182 automatically.
- Script: the same line is evaluated, but nothing appears on screen.
To see the result from a script, write print(miles * 1.61) (p. 33).
Order of operations
When an expression has several operators, Python follows the order remembered as PEMDAS (pp. 33–34):
- Parentheses are evaluated first.
(1+1)**(5-2) is 8, and 2 * (3-1) is 4.
- Exponentiation comes next.
1 + 2**3 is 9, not 27, because the power is done before the addition.
- Multiplication and division come before addition and subtraction.
2*3-1 is 5, and 6+4/2 is 8.
- Operators of equal rank go from left to right, except exponentiation.
The left-to-right rule matters in degrees / 2 * pi. Python divides by 2 first, then multiplies by pi. That is not the same as dividing by 2π. To divide by 2π, write degrees / 2 / pi or use parentheses (p. 34). If you are unsure about the order, parentheses make your intent clear (p. 34).
Operations on strings
Most math operators do not work on strings, even strings that look like numbers. So 'eggs'/'easy' and 'chinese'-'food' are illegal (p. 34). Two operators are exceptions:
+ performs concatenation, joining strings end to end. 'throat' + 'warbler' gives 'throatwarbler'.
* performs repetition. 'Spam'*3 gives 'SpamSpamSpam'. When one operand is a string, the other must be an integer. This matches the idea that 4×3 equals 4+4+4 (p. 34).
Comments
A comment starts with #. Python ignores everything from the # to the end of the line. Comments can sit on their own line or at the end of a line of code (p. 35). Their purpose is to help human readers.
The best comments explain why the code does something, not what it does, because a reader can usually see what the code does. For example, v = 5 # assign 5 to v is useless. v = 5 # velocity in meters/second is useful, because it adds information the code lacks (p. 35).
Good variable names can reduce the need for comments. But very long names make expressions hard to read, so you have to balance the two (p. 35).
Three kinds of errors
Knowing the type of an error helps you find it faster (p. 35).
- Syntax error: the code breaks the rules of structure. For example,
8) has an unmatched parenthesis. Python reports the error and refuses to run the program at all.
- Runtime error (exception): the error only appears once the program is already running. These are rare in simple early programs.
- Semantic error: the program runs and shows no error message, but it does the wrong thing. It does exactly what you wrote, not what you meant. These are the hardest to find, because you must work backward from the output to the cause.
Check yourself
- Explain the difference between an expression and a statement. Give one example of each.
- Why is
76trombones an illegal variable name? Why is class = 5 also illegal, even though class contains only letters?
- What does
2 * 3**2 evaluate to, and why? How would you change it so the multiplication happens first?
- You write
x = 10 and then x * 2 in a script file and run it. What do you see on screen? What would you change to see the result?
- A program runs with no error messages but prints the wrong answer. Which kind of error is this, and why is it hard to find?