This page intentionally left blank Python for Software Design


LOGICAL OPERATORS There are three logical operators



tải về 1.38 Mb.
Chế độ xem pdf
trang23/83
Chuyển đổi dữ liệu13.08.2023
Kích1.38 Mb.
#55046
1   ...   19   20   21   22   23   24   25   26   ...   83
- Python for Software Design How to Think Like a Computer Scientist-Cambridge University Press (2009)

5.3
LOGICAL OPERATORS
There are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English. For example, x > 0 and x < 10
is true only if x is greater than 0 and less than 10.
n % 2 == 0 or n % 3 == 0
is true if either of the conditions is true, that is, if the number
is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y
is false, that is, if x is less than or equal to y.
Strictly speaking, the operands of the logical operators should be boolean expres-
sions, but Python is not very strict. Any nonzero number is interpreted as “true.”


48
Conditionals and Recursion
>>> 17 and True
True
This flexibility can be useful, but there are some subtleties to it that might be
confusing. You might want to avoid it (unless you know what you are doing).
5.4
CONDITIONAL EXECUTION
In order to write useful programs, we almost always need the ability to check condi-
tions and change the behavior of the program accordingly. Conditional statements
give us this ability. The simplest form is the if statement:
if x > 0:
print 'x is positive'
The boolean expression after the if statement is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
if
statements have the same structure as function definitions: a header followed by
an indented block. Statements like this are called compound statements.
There is no limit on the number of statements that can appear in the body, but there
has to be at least one. Occasionally, it is useful to have a body with no statements
(usually as a place keeper for code you haven’t written yet). In that case, you can use
the pass statement, which does nothing.
if x < 0:
pass
# need to handle negative values!

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   19   20   21   22   23   24   25   26   ...   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