python3基础4

python3基础4


1 元组tuple() 不允许修改

创建元组及使用

t1 = ()
t2 = (11, 22, 'abc')
print(t2)
print(t2[1])
# t2[1] = 33    ×
# 元组里放可变列表, 列表内容可改
‘’‘
输出
(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)  # 在s4不在s5的元素
print(s4 & s5)  # 共有元素
print(s4 ^ s5)   # 非共有元素
'''
输出
{'d', 'c', 'e', 'a', 'b', 'g'}
{'d', 'b'}
{'a', 'c'}
{'d', 'e', 'g', 'b'}
'''

3 函数

格式

# def 函数(参数):
#     函数体
#     return 返回值

调用

# 函数名(参数)

无参数

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))   # 仅给a传参数
‘’‘
输出
(20, 'jsj')
’‘’

不定项参数

def fun4(*args):
    print(args)


fun4(1, 2, 3, 4, 5, 6)
‘’‘
输出
(1, 2, 3, 4, 5, 6)
’‘’

4 文件

文件读写格式

# f1 = open(filename, 文件模式)  # 打开
# f1.write(文件内容)   # 写
# 文件内容 = f1.read()  # 读
# f1.close  # 关闭

文件模式

w 写 覆盖  
a 追加  
r 读   
wb rb 以二进制格式写入或读取
f2 = open("file1.txt", 'w')  # 不存在 创建 存在直接调用
f2.write('hello')
f2.write('123')
f2.close()

简写 自动关闭

# with open(filename, 文件模式) as f1:
#     f1.write(文件内容)
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))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值