2、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
str = 'hello'
str_iterator=str.__iter__()
l=[1,2,3,'a','b','c']
l_iterator=l.__iter__()
t=(1,2,3,4,5)
t_iterator=t.__iter__()
d = {'k1':111,'k2':222,'k3':333}
d_iterator=d.__iter__()
s = {'aaa','bbb','ccc'}
s_iterator=s.__iter__()
f = open('user.txt','r',encoding='utf-8')
def func(x):
while True:
try:
res=x.__next__()
print(res)
except StopIteration:
break
func(str_iterator)
func(l_iterator)
func(t_iterator)
func(d_iterator)
func(s_iterator)
func(f)
f.close()
3、自定义迭代器实现range功能
def my_range(start,stop,step=1):
while start < stop:
yield start
start+=step
for i in my_range(1,10,3):
print(i)
编写小说阅读程序实现下属功能
一:程序运行开始时显示
0 账号注册
1 登录功能
2 充值功能
3 阅读小说
二:完成下述功能
2.1、账号注册
- 针对文件db.txt,内容格式为:“用户名:密码:金额” 完成注册功能
2.2、充值功能
三:文件story_class.txt存放类别与小说文件路径,如下,读出来后可用eval反解出字典
{“0”:{“0”:[“倚天屠狗记.txt”,3],“1”:[“沙雕英雄转.txt”,10]},“1”:{“0”:[“令人羞耻的爱.txt”,6],“1”:[“二狗的妻子与大草原的故事.txt”,5]},}
3.1、用户登录成功后显示如下内容,根据用户选择,显示对应品类的小说编号、小说名字、以及小说的价格
“”"
0 玄幻武侠
1 都市爱情
2 高效养猪36技
“”"
# 注册功能
def login():
while True:
name = input('请输入用户名: ').strip()
pwd = input('请输入密码: ').strip()
pwd2 = input('请确认密码: ').strip()
if pwd == pwd2:
print('注册成功')
with open('db.txt', 'a', encoding='utf-8')as f:
f.write('%s:%s:0\n' % (name, pwd))
break
else:
print('2次密码输入不一致')
# 登录功能
def register():
sign = True
while sign:
username=input('请输入用户名: ').strip()
password=input('请输入密码: ').strip()
with open('user.txt','r',encoding='utf-8')as f:
l = [line.strip().split(':') for line in f]
dic = {n: [p, m] for n, p, m in l}
if username in dic and pwd == dic[username][0]:
print('登录成功')
sign = False
break
else:
print('用户名或密码错误')
# 充值功能
def recharge(user):
money=input('请输入充值金额: ').strip()
if money.isdigit():
money=int(money)
with open('db.txt','r',encoding='utf-8')as f:
l = [line.strip().split(':') for line in f]
dic = {n: [p, m] for n, p, m in l}
dic[user][1]=int(dic[user][1])
dic[user][1]+=money
with open('db.txt','w',encoding='utf-8')as f:
for n,v in dic.items():
p,m=v
f.write('%s:%s:%s\n'%(n,p,m))
print(f'充值成功{money}元')
else:
print('请输入数字')
story=None
def story_path():
with open('story_class.txt','r',encoding='utf-8')as f:
data=f.read()
res=eval(data)
global story
story=res
story_path()
def show_page():
str='''
0 玄幻武侠
1 都市爱情
2 高效养猪36技
'''
print(str)
choice=input('请输入命令编号: ').strip()
if choice in story:
global names
names=story[choice]
print(names)
elif choice == '2':
print('名称:高效养猪36技 价格:免费')
else:
print('输入的命令不存在')
# 阅读功能
def reading():
# 展示页面
show_page()
# 阅读小说==>未完成
pass
func={
'1':[login,'账号注册'],
'2':[register,'登录功能'],
'3':[recharge,'充值功能'],
'4':[reading,'阅读小说']
}
while True:
print('0 退出')
for k,v in func.items():
print('%s %s'%(k,func[k][1]))
choice=input('请输入命令编号: ').strip()
if choice == '0':
break
elif choice in func:
func[choice][0]()
else:
print('输入的指令不存在')