# format占位 '{} and {} are black'.format('Gin','Vodka') # Gin and Vodka are black '{2} and {1} are black'.format('Gin','Vodka') # 指定索引 # Vodka and Gin are black '{a} and {b} are black'.format(a='Gin',b='Vodka') # 指定参数 # Gin and Vodka are black
li = [1,1,2,3,5,8] se = set(li) # {1,2,3,5,8} li = list(se) # 与list可以互相转化
a = {1,2,3,4} b = {2,3,4} a | b # 并集 {1,2,3,4} a & b # 交集 {2,3,4} a - b # 在a里面 不在b里面的元素 {1} b <= a # True 判断子集 a <= a # True a.update([4,5,6]) # 更新 {1,2,3,4,5,6} a.remove(1) # 移除指定元素 a.pop() # 弹出并返回首部元素
逻辑结构
判断结构
通过and/or连接多个判断条件
三个及以上判断结果用elif表示
使用: 和缩进表示逻辑从属
1 2 3 4 5 6 7 8 9
a = 90 if a > 100and a <= 200: print('if') elif a == 50or a == 90: print('elif1') elif (a <10and a > 0) or a > 200: print('elif2') else: print('else')
循环结构
while 循环
1 2 3 4 5 6 7 8
a = 0 while a < 5: print(a) a += 1
se = {'Gin','Vodka','Bourbon'} while se: print(se.pop())
for循环
1 2 3 4 5 6 7
for i inrange(1,5): print(i)
di = {'Gin':'black','Vodka':'black','Bourbon':'red'} for key in di.keys(): print(di[key])
defprint_value(a): print('The value of a is ',a) defadd_value(a=1,b=2): # 为参数设置默认值 print('a+b is ',a+b) defadd_number(a,*args): # 接受不定个数的参数 b = 0 for i in args: a += i b += a return a,b # 返回值可以有多个 a,b = add_number(1,2,3) print (a,b) # 6 9 defadd_2(a,**kwargs): # **kwargs可传入不定个数的key-value对 for arg,value in kwargs.items(): print(arg,value) add_2(1,x=2,y=3) # x 2 # y 3
包
1 2 3 4 5 6 7 8
%%writefile test.py # writefile用于在jupyter中新建文件
value = 10010
deftest_function(): print('success')
1 2 3 4 5 6 7 8 9 10 11 12
# 导入包 import test as te # 整个导入包 调用时需用te. print(te.value) # 10010 te.test_function() # success
from test import value,test_function # 导入包中的部分变量和函数 直接使用无需. print(value) # 10010 te.test_function() # success
from test import * # 导入包中的部分变量和函数 直接使用无需. print(te.value) # 10010 te.test_function() # success