Python 小技巧

1.一行代码实现1-100之和

sum1 = sum(range(0, 101))
print(sum1)

2. 如何在函数内部修改全局变量

a = 5
def fn():
# a = 3
global a
a = 8
print(a)

fn()
print(“out function:”)
print(a)

3. 字典删除键和合并两个字典

dic = {“name”: “zs”, “age”: 18}
del dic[“name”]
print(dic)
dic2 = {“name”: “ls”}
dic.update(dic2)
print(dic)

4. python写文件

f = open(‘test.txt’, ‘w’)
f.write(‘Hello, world!’)
f.close()
with open(‘test.txt’, ‘w’) as f:
f.write(‘Hello, Python!’)