捕获异常
a = 10
try:
a / 0
except:
print("error")
迭代器
#迭代器,往前访问元素
list_ = [1,2,3,4]
it = iter(list_)
'''
for x in it:
print(x,end="..")
'''
while True:
try:
print (next(it))
except:
break
#生成器
#普通输出斐波那契数列
def fab(max):
n , a, b = 0, 0, 1
while n<max:
print(b)
a ,b = b ,a+b
n = n+1
fab(6)
#提高复用性,使用List
def fab(max):
n , a, b = 0, 0, 1
L = []
while n<max:
L.append(b)
print(L)
a ,b = b ,a+b
n = n+1
return L
for n in fab(6):
print (n)
#使用生成器,yield 类似于断点
def fab(max):
n , a, b = 0, 0, 1
while True:
if (n>max):
return
yield a #暂停函数并返回a的值
yield b #暂停函数并返回b的值
a ,b = b ,a+b
#print('a = %d,b = %d'%(a,b))
n = n+1
f = fab(8)
while True:
try:
print (next(f),end=" ")#next继续调用函数
except:
break
格式
#str.formate
print('{}网址:"{}"!'.format('百度','www.baidu.com'))
print('{1} and {0}'.format('Tom','Jerry'))
print('{mao} and {shu}'.format(mao = 'Tom', shu = 'Jerry'))
import math
print('PI的值近似为{0:.3f}。'.format(math.pi))