This page intentionally left blank Python for Software Design


OPERATORS AND OPERANDS Operators



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

2.5
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 +, -, *, / and ** perform addition, subtraction, multiplication, division
and exponentiation, as in the following examples:
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
In some other languages, ˆ 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 wiki.python.org/moin/BitwiseOperators.
The division operator might not do what you expect:
>>> minute = 59
>>> minute/60
0
The value of minute 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.0, the result of this division is a float. The new operator // performs integer division.


2.7 Order of Operations
15
If either of the operands is a floating-point number, Python performs floating-point
division, and the result is a float:
>>> minute/60.0
0.98333333333333328
2.6
EXPRESSIONS
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 x has been assigned a value):
17
x
x + 17
If you type an expression in interactive mode, the interpreter evaluates it and displays
the result:
>>> 1 + 1
2
But in a script, an expression all by itself doesn’t do anything! This is a common
source of confusion for beginners.
Exercise 2.2
Type the following statements in the Python interpreter to see what they do:
5
x = 5
x + 1
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.

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   7   8   9   10   11   12   13   14   ...   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