Skip to content

Commit e3c1a7a

Browse files
author
wolf
committed
chapter05
1 parent 14e0907 commit e3c1a7a

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,108 @@
11
\chapter{条件语句和递归}
2+
3+
\section{ 模操作符}
4+
5+
\index{modulus operator 模操作符}
6+
\index{operator!modulus 操作符!模}
7+
8+
模操作符用于两个整数,第一个操作数除以第二个操作数产生余数。在Python
9+
中,模操作符是一个百分号(\verb"%")。语法的格式和其他的操作符相同。
10+
11+
\beforeverb
12+
\begin{verbatim}
13+
>>>quotient = 7 / 3
14+
>>>print quotient
15+
2
16+
>>>remainder = 7 % 3
17+
>>>print remainder
18+
1
19+
\end{verbatim}
20+
\afterverb
21+
22+
7除以3等于2余1。\\
23+
24+
模操作符是非常有用的,比如,你可以查看一个数是否可以被另一个数整除---
25+
如果{\tt x \% y}是0,{\tt x}就可以被{\tt y}整除。\\
26+
27+
\index{divisibility 整除}
28+
29+
你也可以用模运算来提取整数的最右边的数字。比如,{\tt x \% 10 }得到{\tt x}的最右面的一个数字\footnote{译注:个位数}(以十为底)。类似地,
30+
{\tt x \% 100}得到最后的两位数字\footnote{十位和个位的数字}。
31+
32+
\section{布尔表达式}
33+
\index{boolean expression 布尔表达式}
34+
\index{expression!boolean}
35+
\index{logical operator 逻辑运算符}
36+
\index{operator!logical}
37+
38+
布尔表达式的结果要么是真(true),要么为假(false)。下面的例子是使用
39+
{\tt ==}运算符,比较两个操作数,如果相等则结果为{\tt True},否则为{\tt False}:
40+
41+
\beforeverb
42+
\begin{verbatim}
43+
>>> 5 == 5
44+
True
45+
>>> 5 == 6
46+
False
47+
\end{verbatim}
48+
\afterverb
49+
50+
{\tt True}和{\tt False}是两个特殊的值,属于{\tt bool}类型;他们不是
51+
字符串:
52+
53+
\index{True special value True特殊值}
54+
\index{False special value False特殊值}
55+
\index{specail value!True}
56+
\index{special value!False}
57+
\index{bool type bool类型}
58+
\index{type!bool}
59+
60+
\beforeverb
61+
\begin{verbatim}
62+
>>> type(True)
63+
<type 'bool'>
64+
>>> type(False)
65+
<type 'bool'>
66+
\end{verbatim}
67+
\afterverb
68+
69+
{\tt ==}运算符是关系运算符中的一个,其他的还有:
70+
71+
\beforeverb
72+
\begin{verbatim}
73+
x != y # x is not equal to y
74+
x > y # x is greater than y
75+
x < y # x is less than y
76+
x >= y # x is greater than or equal to y
77+
x <= y # x is less than or equal to y
78+
\end{verbatim}
79+
\afterverb
80+
81+
82+
尽管你可能很熟悉这些运算符,他们在Python中的表示方法和数学中的有很大
83+
的不同。一个常见的错误是只使用一个{\tt =}号,而不是两个{\tt ==}号。
84+
记住{\tt =}是赋值操作符,{\tt ==}是关系运算符。而且,Python中没有这样
85+
的符号{\tt =<}或者{\tt =>}\footnote{在FP(functional programming中可能
86+
会遇到这个符号}。
87+
88+
\index{relational operator 关系运算符}
89+
\index{operator!relational}
90+
91+
\section{逻辑运算符}
92+
\index{logical operator 逻辑运算符}
93+
\index{operator!logical}
94+
95+
有三个逻辑运算符:{\tt and},{\tt or}和{\tt not}。这些操作符的意思和
96+
在英语中的意思差不多。比如,{\tt x > 0 and x < 10}为真,仅当{\tt x}
97+
大于0小于10\footnote{译注:在Python中,更pythonic的写法是 0 < x < 10
98+
。 这样的符号对于c/c++背景的程序员来说,有点陌生,在c/c++等值的分别
99+
\&\&, || ,!}。
100+
101+
\index{and operator and运算符}
102+
\index{or operator or运算符}
103+
\index{not operator not运算符}
104+
\index{operator!and}
105+
\index{operator!or}
106+
\index{operator!not}
107+
108+

0 commit comments

Comments
 (0)