This page intentionally left blank Python for Software Design


Conditionals and Recursion 5.1



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

5
Conditionals and Recursion
5.1
MODULUS OPERATOR
The modulus operator works on integers and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent
sign (%). The syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. For example, you can
check whether one number is divisible by another – if x % y is zero, then x is
divisible by y.
Also, you can extract the right-most digit or digits from a number. For example,
x % 10
yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two
digits.
5.2
BOOLEAN EXPRESSIONS
boolean expression is an expression that is either true or false. The following
examples use the operator ==, which compares two operands and produces True if
they are equal and False otherwise:
46


5.3 Logical Operators
47
>>> 5 == 5
True
>>> 5 == 6
False
True
and False are special values that belong to the type bool; they are not strings:
>>> type(True)

>>> type(False)

The == operator is one of the comparison operators; the others are:
x != y
# x is not equal to y
x > y
# x is greater than y
x < y
# x is less than y
x >= y
# x is greater than or equal to y
x <= y
# x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are
different from the mathematical symbols. A common error is to use a single equal
sign (=) instead of a double equal sign (==). Remember that = is an assignment
operator and == is a comparison operator. There is no such thing as =< or =>.

tải về 1.38 Mb.

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