功能要求:
(1)1,5,10元纸币或硬币
(2)饮料只有橙汁,椰汁,矿泉水,早餐奶,售价分别为3.5,4,2,4.5
(3)实现功能:用户投钱和选择饮料,并通过判断之后,给用户吐出饮料和零钱
思路1:
(1)先选择商品
(2)先投币
缺陷:1次只能购买一瓶饮料
def vending_machine(): data = {‘橙汁‘:3.5,‘椰汁‘:4,‘矿泉水‘:2,‘早餐奶‘:4.5} choose = input(‘请输入你要购买的饮料或投入1,5,10元纸币或硬币:‘) # 先选择商品 if choose in data.keys(): price = data[choose] print("{0}的售价为:{1}元".format(choose,price)) money =int(input("请投入1,5,10元纸币或硬币:")) while money not in (1, 5, 10): money = int(input("支付投放无效,请投入1,5,10元纸币或硬币:")) break if money < price: print("投放金额不足,还差{0}元,请继续投放".format(price - money)) money1 = int(input("请继续投入1,5,10元纸币或硬币:")) while money1 not in (1, 5, 10): money1 = int(input("支付投放无效,请投入1,5,10元纸币或硬币:")) break money += money1 if money == price: print("请取出你的{0}饮料".format(choose)) elif money > price: print("请取出你的{0}饮料".format(choose)) print("请取出你的找零{0}".format(money - price)) # 先投钱 else: money = int(choose) if money in (1, 5, 10): drink = input("请选择你想要的饮料:") price = data[drink] print("{0}的售价为:{1}元".format(drink, price)) while money < price: print("投放金额不足,还差{0}元,请继续投放".format(price - money)) money1 = int(input("请继续投入1,5,10元纸币或硬币:")) while money1 not in (1, 5, 10): money1 = int(input("支付投放无效,请重新投入1,5,10元纸币或硬币:")) break if money1 in (1, 5, 10): money += money1 break if money == price: print("请取出你的{0}饮料".format(drink)) elif money > price: print("请取出你的{0}饮料".format(drink)) print("请取出你的找零{0}".format(money - price)) else: print("投放无效,请重新投入1,5,10元纸币或硬币:") else: print("投放无效,请输入你要购买的饮料或投入1,5,10元纸币或硬币:") vending_machine() vending_machine()
测试结果:
方法2:
drinks = {‘1‘:3.5,‘2‘:4,‘3‘:2,‘4‘:4.5} # 用户选择饮料 total = 0 # 存储购买饮料的总金额 while True: choose = input("请选择你要购买的饮料:1:橙汁,2:椰汁,3:矿泉水,4:早餐奶 q:退出") if choose in drinks.keys(): total += drinks[choose] elif choose == ‘q‘: print("退出选择饮料") break else: print("你输入的选项不存在") # 用户投币 toubi = 0 # 投币总额 while True: money = input("请继续投入1,5,10元纸币或硬币,按q退出投币!") if money in (‘1‘,‘5‘,‘10‘): toubi += int(money) if toubi>total: print("你刚刚购买的{0}元饮料,你已支付{1}元,找零{2}".format(total,toubi,toubi-total)) elif toubi<total: print("你刚刚购买的{0}元饮料,你已支付{1}元,还需支付{2}".format(total, toubi,total-toubi)) else: print("你刚刚购买的{0}元饮料,你已支付{1}元,已支付完毕".format(total, toubi)) elif money ==‘q‘: break else: print("你输入的选项不存在")
测试结果:
原文地址:https://www.cnblogs.com/kite123/p/11691347.html
时间: 2024-10-16 16:44:49