1.2.3. 控制流¶
Controls the order in which the code is executed.
1.2.3.1. if/elif/else ¶
>>> if 2**2 == 4:
... print('Obvious!')
...
Obvious!
Blocks are delimited by indentation
在Python解释器中键入以下行,并小心保持缩进深度。Ipython shell在冒号:
符号后自动增加缩进深度;要减小缩进深度,使用Backspace键向左移动四个空格。Press the Enter key twice to leave the logical block.
>>> a = 10
>>> if a == 1:
... print(1)
... elif a == 2:
... print(2)
... else:
... print('A lot')
A lot
缩进在脚本中也是强制性的。作为练习,在脚本condition.py
中重新键入相同缩进的上面的行,并在Ipython中使用run condition.py
执行这个脚本。
1.2.3.2. for/range ¶
Iterating with an index:
>>> for i in range(4):
... print(i)
0
1
2
3
但是最常见的,在值上迭代更具可读性:
>>> for word in ('cool', 'powerful', 'readable'):
... print('Python is %s' % word)
Python is cool
Python is powerful
Python is readable
1.2.3.3. while/break/continue ¶
Typical C-style while loop (Mandelbrot problem):
>>> z = 1 + 1j
>>> while abs(z) < 100:
... z = z**2 + 1
>>> z
(-134+352j)
More advanced features
break
for/while循环:
>>> z = 1 + 1j
>>> while abs(z) < 100:
... if z.imag == 0:
... break
... z = z**2 + 1
continue
循环的下一次迭代:
>>> a = [1, 0, 2, 4]
>>> for element in a:
... if element == 0:
... continue
... print(1. / element)
1.0
0.5
0.25
1.2.3.4. 条件表达式¶
if <OBJECT> : |
|
---|---|
a == b : | 测试相等性: >>> 1 == 1.
True
|
a is b : | Tests identity: both sides are the same object: >>> 1 is 1.
False
>>> a = 1
>>> b = 1
>>> a is b
True
|
a in b : | For any collection >>> b = [1, 2, 3]
>>> 2 in b
True
>>> 5 in b
False
If |
1.2.3.5. 高级迭代¶
1.2.3.5.1. 迭代任何序列 ¶
你可以遍历任何序列(字符串、列表、字典中的键、文件中的行,...):
>>> vowels = 'aeiouy'
>>> for i in 'powerful':
... if i in vowels:
... print(i)
o
e
u
>>> message = "Hello how are you?"
>>> message.split() # returns a list
['Hello', 'how', 'are', 'you?']
>>> for word in message.split():
... print(word)
...
Hello
how
are
you?
Few languages (in particular, languages for scientific computing) allow to loop over anything but integers/indices. 使用Python,可以完全只循环感兴趣的对象,而不必麻烦你经常不关心的索引。This feature can often be used to make code more readable.
Warning
修改你正在迭代的序列是不安全的。
1.2.3.5.2. 跟踪计数¶
常见任务是在序列上进行迭代,同时跟踪元素编号。
可以使用while循环与计数器,如上。Or a for loop:
>>> words = ('cool', 'powerful', 'readable') >>> for i in range(0, len(words)): ... print((i, words[i])) (0, 'cool') (1, 'powerful') (2, 'readable')
But, Python provides a built-in function -
enumerate
- for this:>>> for index, item in enumerate(words): ... print((index, item)) (0, 'cool') (1, 'powerful') (2, 'readable')
1.2.3.6. 列表推导式¶
>>> [i**2 for i in range(4)]
[0, 1, 4, 9]
练习
Compute the decimals of Pi using the Wallis formula: