1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python基础-小程序练习(跳出多层循环 购物车 多级菜单 用户登录)

Python基础-小程序练习(跳出多层循环 购物车 多级菜单 用户登录)

时间:2019-03-30 15:30:33

相关推荐

Python基础-小程序练习(跳出多层循环 购物车 多级菜单 用户登录)

一、 从第3层循环直接跳出所有循环

break_flag = Falsecount = 0while break_flag == False:print("-第一层")while break_flag == False:print("第二层")while break_flag == False:count += 1if count > 10:break_flag = Trueprint("第三层")print("keep going...")

with break_flag

# break_flag = Falsecount = 0while count < 3:print("-第一层")while count < 3:print("第二层")while count <= 10:count += 1# if count > 10:#break_flag = Trueprint("第三层")print("keep going...")

without break_flag

二、 购物车程序

goods_list = [['Iphone7',5800],['Coffee',30],['Book',99],['Bike',199],['Vivi X9',2499]]#商品列表shopping_cart = []#用户购物车列表salary = int(input('input your salary:')) #用户薪水m = salaryk = 0while True:index = 0for goods in goods_list: #打印商品列表print(index,goods)index += 1choice = input('>>>:').strip()if choice.isdigit():choice = int(choice)if choice >= 0 and choice < len(goods_list):goods = goods_list[choice]if goods[1] <= salary:#判断用户是否带了足够的钱来支付所选商品shopping_cart.append(goods)salary -= goods[1]print('Add goods '+str(goods[0])+' into shopping cart! Your current balance:'+str(salary))else:print('No enough money!The price is:'+str(goods[1])+'! Need more:'+str(goods[1]-salary))else:print('Have no this goods!')elif choice == 'q':print('----------Your shopping cart----------')print('ID goods quantity price total')for i in range(len(goods_list)):j = shopping_cart.count(goods_list[i])if j > 0 :k += 1print(k,'\t',goods_list[i][0],'\t',j,'\t\t',goods_list[i][1],'\t',j * goods_list[i][1])print('Total price is:',m - salary)breakelse:print('Have no this goods')

购物车程序

goods_list = [['Iphone7',5800],['Coffee',30],['Book',99],['Bike',199],['Vivi X9',2499]] # 商品列表shopping_cart = {} # 用户购物车列表从列表变为字典salary = int(input('input your salary:')) # 用户薪水# m = salary #不需要此项# k = 0 #用户购物车商品打印ID,移动位置至打印循环外while True:index = 0for goods in goods_list: # 打印商品列表print(index, goods)index += 1choice = input('>>>:').strip()if choice.isdigit(): # 判断是否为数字choice = int(choice)if choice >= 0 and choice < len(goods_list): # 商品存在goods = goods_list[choice]if goods[1] <= salary: # 判断用户是否带了足够的钱来支付所选商品if goods[0] in shopping_cart: # 之前买过shopping_cart[goods[0]][1] += 1 # 购物数量加1else:shopping_cart[goods[0]] = [goods[1], 1] # 创建一条新增商品的购买记录salary -= goods[1] # 扣钱print('Add goods ' + str(goods[0]) + ' into shopping cart! Your current balance:' + str(salary))else:print('No enough money!The price is:' + str(goods[1]) + '! Need more:' + str(goods[1] - salary))else:print('Have no this goods!')elif choice == 'q':id_counter = 1 # 初始化商品IDtotal_cost = 0 # 初始化商品总花费print('----------Your shopping cart----------')print('ID goodsquantity pricetotal')for i in shopping_cart:print("%-5s%-10s%-12s%-10s%-s"% (id_counter, i, shopping_cart[i][1], shopping_cart[i][0],shopping_cart[i][0] * shopping_cart[i][1]))id_counter += 1 # 商品ID自加1total_cost += shopping_cart[i][0] * shopping_cart[i][1] # 用户已购商品总花费print('Total price is:', total_cost)breakelse:print('Have no this goods')

购物车程序优化,使用字典

三、多级菜单

要求:

打印省、市、县三级菜单可返回上一级(b,返回)可随时退出程序(q,退出)

menu = {'北京':{'海淀':{'五道口':{'soho':{},'网易':{},'google':{}},'中关村':{'爱奇艺':{},'汽车之家':{},'youku':{},},'上地':{'百度':{},},},'昌平':{'沙河':{'老男孩':{},'北航':{},},'天通苑':{},'回龙观':{},},'朝阳':{},'东城':{},},'上海':{'闵行':{"人民广场":{'炸鸡店':{}}},'闸北':{'火车战':{'携程':{}}},'浦东':{},},'山东':{},}exit_flag = Falsecurrent_layer = menulayers = [menu]while not exit_flag:for k in current_layer:print(k)choice = input(">>:").strip()if choice == "b":current_layer = layers[-1]#print("change to laster", current_layer) layers.pop()elif choice == 'q':breakelif choice not in current_layer:continueelse:layers.append(current_layer)current_layer = current_layer[choice]

View Code

四、用户登陆程序

需求:

最多允许用户尝试登陆3次当同一用户名3次密码均不正确时,锁定该用户

1 with open('account',encoding='utf8') as f_account, open('lockedlist', 'a+') as f_locked: 2l = [] #定义用户名验证列表,存放黑名单数据 3f_locked.seek(0) #"a+"模式打开后,文件位置位于末尾,要遍历文件内容,需要将指针移至文件起始位置 4for locked_info in f_locked.readlines(): #遍历黑名单 5 l.append(locked_info.strip()) #将黑名单数据添加进列表,注意:需要将文件中的换行符脱掉 6 7c = [] #定义用户登录名列表,存储用户尝试的登录名 8count = 1#登陆次数计数器 9flag = True #登陆循环控制开关10while flag and count < 4:11 user = input('Please input username:')#输入用户名12 pwd = input('Please input password:') #输入用户密码13 if user in l: #用户名在黑名单中14 print("This user is in blacklist,can't log in!") #打印提示信息15 continue16 c.append(user)17 for info in f_account: #用户名不在黑名单中,遍历用户登陆文件18 user_name, user_pwd = info.strip().split(',') #将文件中的用户名和登陆密码赋值给判定变量19 if user == user_name:#用户名符合20 if pwd == user_pwd: #对应密码符合21 print('Welcome %s' % user) #打印登陆成功信息22 flag = False#登陆成功,跳出登陆程序23 break24 count += 1 #对应密码不符合,while循环计数器加125 break26 count += 1#用户名不符合,while循环计数器加127 break28if count == 4:#如果不同用户名密码输错3次,关闭程序29 print('More than 3 times wrong!') #打印提示信息30if len(c) == 3 and c[0] == c[1] == c[2]: #如果相同用户名密码输错3次,将该用户名加入黑名单,限制登陆31 print('This user has been locked!')32 f_locked.write(user+'\n')#将错误3次的用户名写入黑名单,注意,加换行符

用户登陆程序

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。