← 学习库 Think Python 2e 目录

Chapter 3

> 来源: Think Python 2e (Allen B. Downey)

> 原页: https://greenteapress.com/thinkpython/html/thinkpython003.html

\

[插图缺失:thinkpython002.html]
[ [](thinkpython004.html)

------------------------------------------------------------------------

Chapter 2   Variables, expressions and statements

2.1   Values and types

A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 1, and 100000007.

These values belong to different types: 1 is an integer, and 100000009 is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

If you are not sure what type a value has, the interpreter can tell you.

100000010

Not surprisingly, strings belong to the type 100 and integers belong to the type 100. Less obviously, numbers with a decimal point belong to a type called 10000, because these numbers are represented in a format called floating-point.

100000014

What about values like 1000 and 10000? They look like numbers, but they are in quotation marks like strings.

100000017

They’re strings.

When you type a large integer, you might be tempted to use commas between groups of three digits, as in 100000018. This is not a legal integer in Python, but it is legal:

100000019

Well, that’s not what we expected at all! Python interprets 100000020 as a comma-separated sequence of integers. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.

2.2   Variables

One 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.

An assignment statement creates new variables and gives them values:

100000021

This example makes three assignments. The first assigns a string to a new variable named 1000000; the second gives the integer 10 to 1; the third assigns the (approximate) value of π to 10.

A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s 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.


[插图缺失:thinkpython003.png]

Figure 2.1: State diagram.


The type of a variable is the type of the value it refers to.

100000026

2.3   Variable names and keywords

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you’ll see why later).

The underscore character, 1, can appear in a name. It is often used in names with multiple words, such as 1000000 or 100000029.

If you give a variable an illegal name, you get a syntax error:

100000030

100000031 is illegal because it does not begin with a letter. 10000 is illegal because it contains an illegal character, 1. But what’s wrong with 10000?

It turns out that 10000 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 2 has 31 keywords:

100000036

In Python 3, 1000 is no longer a keyword, but 10000003 is.

You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.

2.4   Operators and operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

The operators 1, 1, 1, 1 and 10 perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:

100000044

In some other languages, 1 is used for exponentiation, but in Python it is a bitwise operator called XOR. I won’t cover bitwise operators in this book, but you can read about them at 100000046.

In Python 2, the division operator might not do what you expect:

100000047

The value of 100000 is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.

In Python 3, the result of this division is a 10000. The new operator 10 performs floor division.

If either of the operands is a floating-point number, Python performs floating-point division, and the result is a 10000:

100000052

2.5   Expressions and statements

An 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 (assuming that the variable 1 has been assigned a value):

100000054

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.

Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.

2.6   Interactive mode and script mode

One of the benefits of working with an interpreted language is that 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

100000055

The first line assigns a value to 10000, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn 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 actually evaluates the expression, but it doesn’t display the value unless you tell it to:

100000057

This behavior can be confusing at first.

A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute.

For example, the script

100000058

produces the output

100000059

The assignment statement produces no output.

Exercise 1  

Type the following statements in the Python interpreter to see what they do:

100000060

Now put the same statements into 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.7   Order of operations

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. 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 rules of precedence for other operators. If I can’t tell by looking at the expression, I use parentheses to make it obvious.

2.8   String operations

In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

100000071

The 1 operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:

100000073

The output of this program is 100000074.

The 1 operator also works on strings; it performs repetition. For example, 10000007 is 100000077. If one of the operands is a string, the other has to be an integer.

This use of 1 and 1 makes sense by analogy with addition and multiplication. Just as 100 is equivalent to 10000, we expect 10000008 to be the same as 100000083, and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?

2.9   Comments

As 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 1 symbol:

100000085

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

100000086

Everything from the 1 to the end of the line is ignored—it has no effect on 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 much more useful to explain why.

This comment is redundant with the code and useless:

100000088

This comment contains useful information that is not in the code:

100000089

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.10   Debugging

At this point the syntax error you are most likely to make is an illegal variable name, like 10000 and 10000, which are keywords, or 1000000 and 100, which contain illegal characters.

If you put a space in a variable name, Python thinks it is two operands without an operator:

100000094

For syntax errors, the error messages don’t help much. The most common messages are 100000095 and 100000096, neither of which is very informative.

The runtime error you are most likely to make is a “use before def;” that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong:

100000097

Variables names are case sensitive, so 10000 is not the same as 10000.

At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 1/2 π, you might be tempted to write

100000100

But the division happens first, so you would get π / 2, which is not the same thing! There is no way for Python to know what you meant to write, so in this case you don’t get an error message; you just get the wrong answer.

2.11   Glossary

value:

One of the basic units of data, like a number or string, that a program manipulates.

type:

A category of values. The types we have seen so far are integers (type 100), floating-point numbers (type 10000), and strings (type 100).

integer:

A type that represents whole numbers.

floating-point:

A type that represents numbers with fractional parts.

string:

A type that represents sequences of characters.

variable:

A name that refers to a value.

statement:

A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.

assignment:

A statement that assigns a value to a variable.

state diagram:

A graphical representation of a set of variables and the values they refer to.

keyword:

A reserved word that is used by the compiler to parse a program; you cannot use keywords like 10, 100, and 10000 as variable names.

operator:

A special symbol that represents a simple computation like addition, multiplication, or string concatenation.

operand:

One of the values on which an operator operates.

floor division:

The operation that divides two numbers and chops off the fraction part.

expression:

A combination of variables, operators, and values that represents a single result value.

evaluate:

To simplify an expression by performing the operations in order to yield a single value.

rules of precedence:

The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.

concatenate:

To join two operands end-to-end.

comment:

Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.

2.12   Exercises

Exercise 2  

Assume that we execute the following assignment statements:

100000107

For each of the following expressions, write the value of the expression and the type (of the value of the expression).

  1. 1000001
  2. 100000109
  3. 10000011
  4. 100000111
  5. 100000112

Use the Python interpreter to check your answers.

Exercise 3  

Practice using the Python interpreter as a calculator:

  1. The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5? Hint: 392.7 is wrong!
  2. Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
  3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

Contribute

If you would like to make a contribution to support my books, you can use the button below. Thank you!

Pay what you want:

Small $1.00 USD Medium $5.00 USD Large $10.00 USD X-Large $20.00 USD XX-Large $50.00 USD

Are you using one of our books in a class?

We'd like to know about it. Please consider filling out this short survey.


------------------------------------------------------------------------

\

[插图缺失:thinkpython002.html]
[ [](thinkpython004.html)

---

← Chapter 2Chapter 4 →