python3基础4
1 元组tuple() 不允许修改
创建元组及使用
t1 = ()
t2 = (11, 22, 'abc')
print(t2)
print(t2[1])
‘’‘
输出
(11, 22, 'abc')
22
’‘’
2 集合set{} 无序 不能用切片
创建
s1 = {}
print(type(s1))
s2 = set()
print(type(s2))
‘’‘
输出
<class 'dict'>
<class 'set'>
’‘’
自动去重
s3 = {'a', 'a', 'b', 'c', 'c'}
print(s3)
‘’‘
输出
{'a', 'c', 'b'}
’‘’
运算 | - & ^
s4 = {'a', 'b', 'c', 'd'}
s5 = {'a', 'e', 'c', 'g'}
print(s4 | s5)
print(s4 - s5)
print(s4 & s5)
print(s4 ^ s5)
'''
输出
{'d', 'c', 'e', 'a', 'b', 'g'}
{'d', 'b'}
{'a', 'c'}
{'d', 'e', 'g', 'b'}
'''
3 函数
格式
调用
无参数
def fun1():
print("hello world")
fun1()
‘’‘
输出
hello world
’‘’
有参数
def fun2(a):
b = a*10
return b
x = fun2(5)
print(x)
‘’‘
输出
50
’‘’
默认参数&多个参数
def fun3(a, c='jsj'):
b = a*10
return b, c
print(fun3(2))
‘’‘
输出
(20, 'jsj')
’‘’
不定项参数
def fun4(*args):
print(args)
fun4(1, 2, 3, 4, 5, 6)
‘’‘
输出
(1, 2, 3, 4, 5, 6)
’‘’
4 文件
文件读写格式
文件模式
w 写 覆盖
a 追加
r 读
wb rb 以二进制格式写入或读取
f2 = open("file1.txt", 'w')
f2.write('hello')
f2.write('123')
f2.close()
简写 自动关闭
with open("file2.txt", 'a') as f3:
f3.write("1112236")
with open("file2.txt", 'r') as f3:
print(f3.read())
练习
对不定参数求和
def add_fun(*args):
sum_n = 0
for i in args:
try:
i = int(i)
sum_n += i
except Exception:
print("error")
exit()
return sum_n
print(add_fun(1, 9, 3))