命题:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
伪代码
shopping_car = [] balance = input usr‘s balance (check parameter‘s legality) while TRUE { show commodity list choice = user input if choice.isdigit { if choice > number of commodity{ print("invalid input") continue } item = commodity[choice] if item.price < balance { shopping_car.append(item) balance -= item.price print("item add success, balance:%d") } else{ print("balance is not enough!") } } else{ if choice == ‘q‘{ print("your shopping things & balance") break }else { print("invalid input") } } }
源码:
#! /usr/local/bin/python3.5 import sys commodity = [ ("iphone", 5888), ("MacBook", 12888), ("StarBark", 60), ("Bike", 1000) ] shopping_car = [] while True: balance = input("input your balance:") if balance.isdigit(): #检查是不是整形 balance = int(balance) #类型转换整形 break else: if balance == ‘q‘: sys.exit(0) else: print("----->Invalied input!!!") while True: for index, cl in enumerate(commodity): #对于list,该函数将其转换为索引序列 print("\n", index, cl) uc = input("Input your choice:") #输入选择 if uc.isdigit(): uc = int(uc) if uc < len(commodity) and uc >=0: item = commodity[uc] if item[1] <= balance: shopping_car.append(item) balance -= item[1] print("%s add shopping car sucess!"%item[0]) else: print("your balance is not enough!") else: print("------->Invalid input!") elif uc == ‘q‘: print("----------shopping list-----------") for c in shopping_car: print(c) print("your balance:%d"%balance) break; else: print("------->Invalid option")
原文地址:https://www.cnblogs.com/yangdadahome/p/8149896.html
时间: 2024-10-08 18:58:14