Python文档学习笔记(3)--流程控制语句 (1)
while
语句
else可选
i = 0 while i <= 3: print("循环{}次".format(i)) i += 1 else: print("结束")
if
语句
可以有0个或多个 elif
块,,并且 else
块是可选的
一个if
... elif
... elif
...序列 是对其他语言的switch
or case
语句的替代方案。
>>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') ... More
for
语句
Python 的 for
语句可以按照元素出现的顺序迭代任何序列(列表或字符串)
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
如果要在循环内修改正在迭代的序列(例如,复制所选的项目),建议首先创建原序列的拷贝
import time
words = ['cat', 'window', 'defenestrate']
print(id(words)) #id()查内存地址
b = words[:]
for w in b: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
print(id(b),words)
time.sleep(1)
[:]浅拷贝后内存地址变了
267616368200
267616357448 ['defenestrate', 'cat', 'window', 'defenestrate']
range()
函数
包含起点不包含终点,可以是负数,第三个参数可以指定一个步进值。
由 range()
返回的对象的行为就像它是一个列表,但事实上它不是。它是一个对象。当您遍历它时, 它会返回所需的序列连续项。但它并不真的生成了列表,从而节省了空间
>>> for i in range(5): ... print(i) ... 0 1 2 3 4
range(5, 10)
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
要迭代序列的索引,您可以将range()
和len()
组合如下:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
或者是这样;
enumerate
(iterable, start=0)
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
break
和continue
语句,以及循环中else
子句
break
语句用于跳出最近的 for
或 while
循环。
循环语句可以有一个 else
子句;当(for
)循环迭代完整个列表或(while
)循环条件变为假,而非由break
语句终止时,就会执行这个else语句。
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
continue
语句表示继续下一次迭代:
>>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found a number", num) Found an even number 2 Found a number 3 Found an even number 4 Found a number 5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9
pass
语句
pass
语句什么也不做。当语法上需要语句但程序不需要动作时,可以使用它
>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...
>>> class MyEmptyClass: ... pass ...
>>> def initlog(*args):
... pass # Remember to implement this!
...