Chapter 2 Variables, expressions and statementsOne of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. 2.1 Assignment statementsAn assignment statement creates a new variable and gives it a value: >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.1415926535897932 This example makes three assignments. The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi. A common way to represent variables on paper is to write the name with an arrow pointing to its value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable’s state of mind). Figure 2.1 shows the result of the previous example. 2.2 Variable namesProgrammers generally choose names for their variables that are meaningful—they document what the variable is used for. Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lower case for variables names. The underscore character, If you give a variable an illegal name, you get a syntax error: >>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax 76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what’s wrong with class? It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python 3 has these keywords: False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise You don’t have 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 know. 2.3 Expressions and statementsAn expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions: >>> 42 42 >>> n 17 >>> n + 25 42 When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42. A statement is a unit of code that has an effect, like creating a variable or displaying a value. >>> n = 17 >>> print(n) The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values. 2.4 Script modeSo far we have run Python in interactive mode, which means that you interact directly with the interpreter. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy. The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py. If you know how to create and run a script on your computer, you are ready to go. Otherwise I recommend using PythonAnywhere again. I have posted instructions for running in script mode at http://tinyurl.com/thinkpython2e. Because Python provides both modes, you can test bits of code in interactive mode before you put them in a script. But there are differences between interactive mode and script mode that can be confusing. For example, if you are using Python as a calculator, you might type >>> miles = 26.2 >>> miles * 1.61 42.182 The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. It turns out that a marathon is about 42 kilometers. But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python evaluates the expression, but it doesn’t display the result. To display the result, you need a print statement like this: miles = 26.2 print(miles * 1.61) This behavior can be confusing at first. To check your understanding, type the following statements in the Python interpreter and see what they do: 5 x = 5 x + 1 Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again. 2.5 Order of operationsWhen an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
I don’t work very hard to remember the precedence of operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious. 2.6 String operationsIn general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal: 'chinese'-'food' 'eggs'/'easy' 'third'*'a charm' But there are two exceptions, + and *. The + operator performs string concatenation, which means it joins the strings by linking them end-to-end. For example: >>> first = 'throat' >>> second = 'warbler' >>> first + second throatwarbler
The * operator also works on strings; it performs repetition.
For example, This use of + and * makes sense by
analogy with addition and multiplication. Just as 4*3 is
equivalent to 4+4+4, we expect 2.7 CommentsAs programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain
in natural language what the program is doing. These notes are called
comments, and they start with the # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60 In this case, the comment appears on a line by itself. You can also put comments at the end of a line: percentage = (minute * 100) / 60 # percentage of an hour 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. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why. This comment is redundant with the code and useless: v = 5 # assign 5 to v This comment contains useful information that is not in the code: v = 5 # velocity in meters/second. Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff. 2.8 DebuggingThree kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.
2.9 Glossary
2.10 ExercisesExercise 1 Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.
Exercise 2
Practice using the Python interpreter as a calculator:
|
ContributeIf you would like to make a contribution to support my books, you can use the button below and pay with PayPal. Thank you!
Are you using one of our books in a class?We'd like to know about it. Please consider filling out this short survey.
|