You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何在输入框内显示剩余金额?调试问题求助

解决Python输入提示中剩余金额显示问题

你的问题核心出在**input()函数的使用方式**上——这个函数只能接收一个字符串参数,但你传了两个参数(提示文本+计算出的剩余金额),这会直接触发语法错误,自然没法正确显示剩余金额。

我们可以通过字符串格式化把剩余金额整合到提示文本里,同时保持金额显示为两位小数的格式,和你之前的代码风格统一。下面是修正后的完整代码:

prod = ["Coffee", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
m = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nYour choices:")
for number in range(0, item_number, 1):
    print(number + 1, prod[number], '{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please enter a choice between (1-4) or hit 0 for exit: ")) -1
if choice < item_number and choice >= 0:
    print("Please enter", "{0:.2f}€".format(cost[choice]), 'in total')
else:
    print("Exiting the program")
    exit(0)
money = float(input("Please fill the remaining amount ; "))
while money < cost[choice]:
    # 关键修改:把剩余金额格式化到提示字符串中
    remaining = cost[choice] - money
    money += float(input(f"You still have to enter {remaining:.2f}€: "))
change = money - cost[choice]
print("Your change {0:.2f}€".format(change))

关键修改说明:

  1. 先单独计算出剩余需要支付的金额remaining = cost[choice] - money
  2. 使用f-string格式化(Python 3.6+支持)把剩余金额以两位小数的格式嵌入到input的提示文本中,用户就能清晰看到还需要补多少钱。
  3. 如果你需要兼容更早的Python版本,也可以用你之前习惯的str.format()写法替代:
    money += float(input("You still have to enter {0:.2f}€: ".format(remaining)))
    

这样修改后,当用户输入的金额不足时,就会正确显示剩余需要支付的金额了。

内容的提问来源于stack exchange,提问作者user4466931

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:57:46