一、Python生成器
Python生成器另一个重要特性,就是能够利用next函数与调用的代码进行交互。yield变成了一个表达式,而值可以通过名为send的新方法来传递:
def psychologist():
print('Please tell me your problems')
while True:
answer = (yield)
if answer is not None:
if answer.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in answer:
print("Ahh that's good, go on")
elif 'bad' in answer:
print("Don't be so negative")
elif answer in ('q', 'quit'):
print("Goodbye")
yield
return
else:
print("Please continue")
if __name__ == "__main__":
print("Starting psychologist session, type 'q' or 'quit' to end session")
freud = psychologist()
for phrase in freud:
problem = input("> ")
freud.send(problem)
二、for...else...语句
在for循环之后使用else子句,可以在循环“自然”结束而不是被break语句终止时执行一个代码块。这一语法在某些情况下很有用,因为它有助于删除一些“哨兵”变量,如果for语句自然结束时用户想要保存信息,可能会需要这些变量。
for number in range(1):
break
else:
print("this will not be printed")
上面这段代码无打印输出,因为是被break语句终止的。
for number in range(1):
pass
else:
print("this will be printed")
该段代码将输出打印输出,因为for语句是自然结束的。