Python学习day3
一、三级菜单程序练习
要求:
1.打印省、市、县三级菜单
2.可返回上一级
3.可随时退出程序
data = {
'北京': {
"昌平": {
"沙河": ["oldboy", "test"],
"甜筒苑": ["链家地产", "我爱我家"]
},
"朝阳": {
"望京": ["奔驰", "陌陌"],
"国贸": ["CICC", "HP"],
"东直门": ["Advent", "飞信"]
},
"海淀": {},
},
'山东': {
"德州": {},
"青岛": {},
"济南": {}
},
'广东': {
"东莞": {},
"常熟": {},
"佛山": {}
}
}
exit_flag = False # 通过控制标识位直接退出
while not exit_flag:
for i in data:
print(i)
choice = input("选择进入1>>:")
if choice in data:
while not exit_flag:
for j in data[choice]:
print("\t", j)
choice2 = input("选择进入2>>:")
if choice2 in data[choice]:
while not exit_flag:
for k in data[choice][choice2]:
print("\t\t", k)
choice3 = input("选择进入3>>:")
if choice3 in data[choice][choice2]:
for l in data[choice][choice2][choice3]:
print("\t\t\t", l)
choice4 = input("最后一层,按b返回>>:")
if choice4 == 'b':
pass
elif choice4 == 'q':
exit_flag = True
if choice3 == 'b':
break
elif choice3 == 'q':
exit_flag = True
if choice2 == 'b':
break
elif choice2 == 'q':
exit_flag = True
二、集合操作
#Author:Fred
list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)#变成集合,并且去除重复的元素排序
list_2 = set([2,6,0,66,22,8,4])
print(list_1,list_2)
'''
#交集
print(list_1.intersection(list_2))
print(list_1)
#并集
print(list_1.union(list_2))
#差集 保留1有的2没用的
print(list_1.difference(list_2))
print(list_2.difference(list_1))
#子集、父集合
list_3 = set([1,3,7])
print(list_3.issubset(list_1))
print(list_1.issuperset(list_3))
print(list_1.issuperset(list_1))
#反向差集,并集去掉交集
print(list_1.symmetric_difference(list_2))
#查询两个集合有没有交集
list_4 = set([5,6,8])
print(list_3.isdisjoint(list_4))
'''
print(list_1 & list_2)#交集&
print(list_1 | list_2)#并集|
print(list_1 - list_2)#差集-
print(list_1 ^ list_2)#对称差集^
list_1.add(999)
list_1.update([888,777,555])
print(list_1)
#print(list_1.pop())
list_1.discard(888)#删除888
print(list_1)
三、文件操作
1.增删查,r,w,a
#Author:Fred
'''
#data = open("yesterday",encoding="utf-8").read()
f = open("yesterday2",'a',encoding="utf-8") #文件句柄
# a=append,w=write,r=read,r+是读写,从最后一个字符开始写,w+是写读,a+是追加写并且可读
#wb是二进制文件的写,还有rb,ab同理
#data = f.read()
f.write("我爱北京天安门,\n")
f.write("天安门上太阳升。\n")
f.close()
'''
f = open("yesterday2",'wb')
f.write("hello\n".encode())#默认是utf-8,现在转换成二进制就可以写入惹
f.close()
#f.truncate(10)#默认从开头截断10个字符,如果从第几个开始截断,那么之前的也会保留下来,seek没有用。
'''
print(f.tell())
print(f.readline(5))
print(f.tell())#计字符的数
f.seek(0)#0代表回到最开始,5代表打印到第一行的第五个元素往后一行
print(f.readline())
print(f.encoding)#打印编码
print(f.fileno())#文件号,不重要
print(f.flush())#暂时缓存下来
#for line in f.readlines():#遍历每行
# print(line.strip())#去除\t转行符
#for i in range(5):#循环 读取前五行
# print(f.readline())
'''
#low的循环
'''
for index,line in enumerate(f.readlines()):#第九行分割出来
if index == 9:
print('-----我是分隔符------')
continue
print(line.strip())
'''
'''
#好的循环
count = 0
for line in f:
if count == 9:
print('-----我是分隔符------')
count += 1
continue
print(line)
count += 1
'''
- 文件修改
#Author:Fred
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
for line in f:
if "肆意的快乐等我享受" in line:
line = line.replace("肆意的快乐等我享受","肆意的快乐等Alex享受")
f_new.write(line)
f.close()
f_new.close()
四、函数
1.test1:
#Author:Fred
#函数
def func1():
print('in the func1')
return 0
#过程
def func2():
print('in the func2')
x = func1()
y = func2()
print('from func1 is %s'%x)
print('from func2 is %s'%y)
2.test2:
#Author:Fred
import time
def logger():
time_format = '%Y-%m-%d %X'#时间的格式
time_current = time.strftime(time_format)#打印时间
with open('a.txt','a+') as f:
f.write('%s end action\n' %time_current)
def test1():
print('in the test1')
logger()
def test2():
print('in the test2')
logger()
def test3():
print('in the test3')
logger()
test1()
test2()
test3()
3.test3:
#Author:Fred
def test1():
print('in the test 1')
#return 0 #结束函数,下面写什么都不执行
def test2():
print('in the test 2')
return 0
def test3():
print('in the test 3')
return 1,'hello',['alex','peiqi'],{'name':'name'}
x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z)
4.test4:
#Author:Fred
def test(x,y):
print(x)
print(y)
test(y=2,x=1)#关键参数不能在位置参数前面
5.test5:
#Author:Fred
def test(x,y=2):#默认参数
print(x)
print(y)
test(1,5)
6.test6:
#Author:Fred
# def test(*args):
# print(args)
# test(1,2,3)
# def test2(**kwargs):#输出字典**kwargs吧关键字参数,转换为字典的方式
# print(kwargs)
# test2(name='alex',age=8,sex='F')
# test2(**{'name':'alex','age':9})
# def test3(name,**kwargs):
# print(name)
# print(kwargs)
# test3('alex',age=18,sex='m')
#*args:接收的N个位置参数,转换成元组形式,**kwargs:接受N个关键字参数,转换成字典的形式
def test4(name,age=18,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
logger("TEST4")
def logger(source):
print("from %s" %source)
test4('alex',age=34,sex='m',hobby='tesla')
五、进度条打印
#Author:Fred
import sys,time
for i in range(20):
sys.stdout.write("$")
sys.stdout.flush()
time.sleep(0.1)
六、with语句
#Author:Fred
import sys
with open("yesterday2","r",encoding="utf-8") as f:#with的作用是自动关闭文件,不用写close
for line in f:
print(line.strip())
七、递归函数
#Author:Fred
def calc(n):
print(n)
if int(n/2) > 0:
return calc(int(n/2))
print("->",n)
calc(10)
八、高阶函数
#Author:Fred
def add(a,b,f):
return f(a) + f(b)
res = add(3,-6,abs)#abs:绝对值
print(res)
九、局部变量小例子global
#Author:Fred
school = "Oldboy edu."#全局变量
def change_name(name):
global school#强制改变全局变量才可以改
school = "Magem"
print("before change",name,school)
name = "Alex li"#name是一个局部变量,只在函数里生效
print("after change",name)
name = 'alex'
change_name(name)
print(name)
print(school)

浙公网安备 33010602011771号