This page intentionally left blank Python for Software Design


Variables, Expressions, and Statements 2.1



tải về 1.38 Mb.
Chế độ xem pdf
trang10/83
Chuyển đổi dữ liệu13.08.2023
Kích1.38 Mb.
#55046
1   ...   6   7   8   9   10   11   12   13   ...   83
- Python for Software Design How to Think Like a Computer Scientist-Cambridge University Press (2009)

2
Variables, Expressions, and Statements
2.1
VALUES AND TYPES
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, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello, World!' 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.
The print statement also works for integers.
>>> print 4
4
If you are not sure what type a value has, the interpreter can tell you.
>>> type('Hello, World!')

>>> type(17)

Not surprisingly, strings belong to the type str and integers belong to the type int.
Less obviously, numbers with a decimal point belong to a type called float, because
these numbers are represented in a format called floating-point.
>>> type(3.2)

10


2.2 Variables
11
What about values like '17' and '3.2'? They look like numbers, but they are in
quotation marks like strings.
>>> type('17')

>>> type('3.2')

They’re strings.
When you type a large integer, you might be tempted to use commas between
groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it is
legal:
>>> print 1,000,000
1 0 0
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-
separated sequence of integers, which it prints with spaces between.
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:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
This example makes three assignments. The first assigns a string to a new vari-
able 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 the variable’s value. This kind of figure is called a state diagram because


12
Variables, Expressions, and Statements
it shows what state each of the variables is in (think of it as the variable’s state of
mind). This diagram shows the result of the previous example:
message
n
pi
17
’And now for something completely different’
3.1415926535897931
To display the value of a variable, you can use a print statement:
>>> print n
17
>>> print pi
3.14159265359
The type of a variable is the type of the value it refers to.
>>> type(message)

>>> type(n)

>>> type(pi)

Exercise 2.1
If you type an integer with a leading zero, you might get a confusing error:
>>> zipcode = 02492
ˆ
SyntaxError: invalid token
Other numbers seem to work, but the results are bizarre:
>>> zipcode = 02132
>>> print zipcode
1114
Can you figure out what is going on? Hint: print the values 01, 010, 0100, and 01000.


2.4 Statements
13
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 (_) can appear in a name. It is often used in names with
multiple words, such as my_name or airspeed_of_unladen_swallow.
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 does not begin with a letter. 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 has 31 keywords

:
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
print
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try
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
STATEMENTS
A statement is a unit of code that the Python interpreter can execute. We have seen
two kinds of statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes it and
displays the result, if there is one.

In Python 3.0, exec is no longer a keyword.


14
Variables, Expressions, and Statements
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
print 1
x = 2
print x
produces the output
1
2
The assignment statement produces no output.

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   6   7   8   9   10   11   12   13   ...   83




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương