苦瓜打怪兽 2023-10-17 18:19 采纳率: 50%
浏览 7
已结题

Python代码看起来很杂乱,如何优化

问题:不知道该怎么继续优化代码,这个代码看起来很冗杂,已经优化了好几次,已经不知道该从何下手了,但是代码看起来还是很杂乱。在此谢过各位。

# -*- coding: utf-8 -*-
#--------------------------------------------------------------题目
"""
购物车
要求
1、让用户输入账户余额
2、自动打印商品名称和价格,
3、判断余额
4、如果余额不足,则提示,并退出
5、同时计算余额是否可以购买至少一个产品,让用户输入产品编号和数量
6、要求可以实现在买了一个产品后可以继续购买其他产品
"""
#--------------------------------------------------------------商品信息与金额计算
""" 商品基本信息 """
information = {
    "巧克力":12,
    "杯子":25,
    "燕麦片":28,
    "兔子":52
    }

moneys = 0

def commodity(number = "inf"):
    while True:
        
        """ 商品信息打印 """
        ref = 0
        if number == "inf":
            print("="*25)
            print("欢迎来到齐齐小卖部")
            print("")
            for name,money in information.items():
                ref += 1
                print(f"{name}{money}元,商品编号{ref}")
            print("="*25)
            break

        """ 计算商品金额 """
        global moneys
        if 1 <= number <= len(information):
            moneys += information[list(information.keys())[number-1]]
            return moneys
            break
        
#-------------------------------------------------------------- 用户购买商品
commodity()
   
""" 模拟用户购物商品 """
n = 0
print("\nprompt:enter 'q' to exit")

while n < len(information):
    number = input(f"\nMay i ask what you need to buy?(enter the number1-{len(information)}):")
    if number.isdigit():
        number = int(number)
        if 1<= number <=len(information):
            moneys = commodity(number)
            n += 1
        else:
            print("please enter an integer number")
    elif number == "q":
        break
    else:
        print("please enter an existing product number!")
    
print(f"\na total of {moneys} yuan is needed")
    
#-------------------------------------------------------------- 用户结账
m = 0
while m < 3:
    
    """ 输入账户余额 """
    user_balance = float(input("please enter your balance:"))
    
    """ 判断余额,最多可支付3次 """
    if user_balance < moneys:
        print("\nbalance is insufficient!Please make a new payment")
        m += 1
    else:
        user_balance -= moneys
        print(f"\nPayment successful, your balance still has {user_balance} yuan")
        break

  • 写回答

2条回答 默认 最新

  • 「已注销」 2023-10-17 22:27
    关注
    
    nl=["巧克力","杯子","燕麦片","兔子"]
    cl=[12,25,28,52]
    moneys=0
    out=[]
    print("="*25+"\n欢迎来到奇奇小卖部\n")
    for i in range(len(cl)):
        print(nl[i]+str(cl[i])+"元,商品编号:"+str(i))
    print("="*25)
    n=0
    print("按q退出")
    while n<len(cl):
        inp=input("你需要什么?")
        if inp=="q":
            break
        try:
            inp=int(inp)
            if moneys>=cl[inp]:
                monyes=moneys-cl[inp]
                print("成功购买"+nl[inp]+"余额"+str(moneys))
                out.append(nl[inp])
                n=n+1
            else:
                print("余额不足")
        finally:
            print("错误的输入")
    print("您购买了"+str(out)+"剩余"+str(moneys)+"元")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月27日
  • 已采纳回答 10月19日
  • 创建了问题 10月17日

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用