格式化字符串:
a=[0,1,2,3,4,5,6,7,8,9]
a[:5:-1] #[9,8,7,6]
an={'a':1,'b':'bin'} r ="%(a)d---%(b)s" % an #1---bin
so = {'name':'god','share':100,'price':29.9} print("{0[name]}==={0[share]}==={0[price]}".format(so))
an={} an[0,2,3]=12 #{(0, 2, 3): 12}
条件表达式
a = x if x>y else y
列表表达式
[x for x in range(10)]
a = [1,65,34,87,34,98,34,23] re = [x if x>50 else 50 for x in a] print(re) #[50, 65, 50, 87, 50, 98, 50, 50]
an =['a','b','c'] b = [1,2,3] print(dict(zip(an,b))) #{'b': 2, 'a': 1, 'c': 3} print(list(zip(an,b))) #[('a', 1), ('b', 2), ('c', 3)] print(tuple(zip(an,b))) #(('a', 1), ('b', 2), ('c', 3)) a=['a','b','c'] for x,y in enumerate(a): print(x,y) #0 a #1 b #2 c
for i in range(5): if i == 3: # print('haha') break else: #1 print('zezeze') print(i) else: #2 print('eeeeeeeeee') for ...else#2 ,只有在循环结束之后,才会执行else#2字句。 如果循环不执行,则立刻执行else#2子句。 如果使用了break语句终止循环,则,不会执行else#1,#2 语句
try...except..else...finally
如果碰到异常,会停止执行代码块,寻找匹配该异常的except子句,如果找到,控制权就会传递给except子句,如果没有找到,异常就会传递给上一级try语句。直至找到匹配该异常的子句,或者到达顶部。
如果引发了异常,控制权先传递给finally代码块,这段执行完毕之后,再引发异常。
try: prnt('zzzz') except Exception as e: if type(e) is NameError: print('nameerror') finally: print('haha')
#nameerror
#haha
函数作用域
i=0;#1431498512 print(id(i)) def foo(): # global i #1431498512 # i =1 #i =1 #1431498544 i #i=0 #1431498512 print('i in',id(i)) print(i) foo() print(i)#0
global和nonlocal
n = 3 def foo(): a=1 n = 1 # print(n) def sma(): # global n; #n = 3 nonlocal n; #n = 1 n +=1 print(n) while a: sma() a =0 foo()