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