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

Python程序仅需一次输入用餐成本却重复请求输入的问题如何修复

问题原因
  • 你当前代码中每次调用get_cost()函数都会触发一次用户输入操作,你在计算小费、税费、总金额、打印每个字段的时候都单独调用了get_cost(),所以会重复要求输入
  • 额外的隐藏问题:print()函数的返回值是None,你把print()的结果赋值给变量后,后续再用这些变量格式化打印会直接报错
修复方案

核心逻辑调整为:仅在程序启动时调用一次get_cost()拿到用餐成本,后续所有计算、打印都复用这个值,不再重复调用输入函数。同时调整各计算函数的逻辑,改为接收用餐成本作为参数计算结果,不需要自己触发输入。

修正后的完整代码
def get_cost():
    meal = float(input('Enter cost of meal: '))
    while meal < 0:
        print('Not possible.')
        meal = float(input('Enter cost of meal: '))
    return meal

# 计算函数改为接收餐费参数,无需自行触发输入
def compute_tip(meal_cost):
    return meal_cost * 0.18

def compute_tax(meal_cost):
    return meal_cost * 0.0825

def compute_grand_total(meal_cost, tip, tax):
    return meal_cost + tip + tax

def display_total_cost(meal_cost, tip, tax, total):
    # 直接使用传入的已计算完成的数值打印,无需重复触发输入或计算
    print('Cost:', format(meal_cost, '.2f'))
    print('Tip:', format(tip, '.2f'))
    print('Tax:', format(tax, '.2f'))
    print('Total:', format(total, '.2f'))

def main():
    # 仅调用一次输入函数获取餐费
    meal_cost = get_cost()
    # 复用餐费计算所有对应金额
    tip = compute_tip(meal_cost)
    tax = compute_tax(meal_cost)
    total = compute_grand_total(meal_cost, tip, tax)
    # 传入所有计算完成的数值直接打印输出
    display_total_cost(meal_cost, tip, tax, total)

main()

运行后仅需要输入一次用餐成本,就会自动输出所有需要的金额字段,不会再重复要求输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:48:01