python3基础知识自学笔记4-流程控制、迭代器、生成器

流程控制

if 控制
if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。 2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。 3、在 Python 中没有 switch - case 语句。

三元运算符:
<表达式1> if <条件> else <表达式2>
编写条件语句时,应该尽量避免使用嵌套语句。嵌套语句不便于阅读,而且可能会忽略一些可能性。

for 遍历
for <循环变量> in <循环对象><语句1>
else:
    <语句2>
else 语句中的语句2只有循环正常退出(遍历完所有遍历对象中的值)时执行。
在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
... 
gallahad the pure
robin the brave

在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
... 
0 tic
1 tac
2 toe

同时遍历两个或更多的序列,可以使用 zip() 组合:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
... 
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
... 
9
7
5
3
1

要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
... 
apple
banana
orange
pear

while 循环
while<条件><语句1>
else<语句2>
breakcontinuepass
break 语句用在 whilefor 循环中,break 语句用来终止循环语句,
即循环条件没有 False 条件或者序列还没被完全递归完,也会停止执行循环语句。    continue 语句用在 whilefor 循环中,
continue 语句用来告诉 Python 跳过当前循环的剩余语句,
然后继续进行下一轮循环。 continue 语句跳出本次循环,
而 break 跳出整个循环。

pass 是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。

迭代器
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。
迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器。

迭代器可以被 for 循环进行遍历:
>>> li = [1, 2, 3]
>>> it = iter(li)
>>> for val in it:
...     print(val)
... 
1
2
3

迭代器也可以用 next() 函数访问下一个元素值:
>>> import sys
>>> 
>>> li = [1,2,3,4]
>>> it = iter(li)
>>> 
>>> while True:
...     try:
...         print (next(it))
...     except StopIteration:
...         sys.exit()
... 
1
2
3
4

生成器
在 Python 中,使用了 yield 的函数被称为生成器(generator)。
跟普通函数不同的是,生成器是一个返回迭代器的函数,
只能用于迭代操作,更简单点理解生成器就是一个迭代器。
在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,
返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。
调用一个生成器函数,返回的是一个迭代器对象。

import sys

def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print(next(f))
    except StopIteration:
        sys.exit()

猜你喜欢

转载自www.cnblogs.com/guiguxiaosheng/p/9456305.html