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

Python小费计算器else分支失效求助:非指定百分比无提示

问题解决:小费计算器的else分支异常

问题原因

你当前的代码用了三个独立的if语句,最后一个else仅和第三个判断20%小费的if绑定。这会导致:

  • 输入10或15时,前两个if执行并输出应付金额,但第三个if条件不成立,会触发else输出错误提示,不符合你只显示金额的预期;
  • 输入非10/15/20的数字时,虽然else会触发错误提示,但输入10/15时的额外错误提示让你误以为功能失效。

修正后的代码

print("\t Welcome to Tip Calculator")

bill = float(input("What was the total bill? $"))

people = int(input("How many people split the bill? "))

tip_percentage = int(input("What percentage tip would you like to give? 10, 15 or 20? "))

tip = bill * tip_percentage / 100

if tip_percentage == 10:
    print(f"Each person should pay: ${(bill + tip) / people:.2f}")
elif tip_percentage == 15:
    print(f"Each person should pay: ${(bill + tip) / people:.2f}")
elif tip_percentage == 20:
    print(f"Each person should pay: ${(bill + tip) / people:.2f}")
else:
    print(f"{tip_percentage} is not a valid percentage!")

关键修改说明

  • 改用if-elif-else链式结构:确保else仅在所有小费比例条件都不满足时触发,输入10/15/20时只会输出对应金额,输入其他数字时才显示错误提示。
  • 修正两处拼写错误:split to改为split the,percantage改为percentage。
  • 优化输出格式:用f-string格式化金额并保留两位小数,让结果更符合货币显示习惯。

内容的提问来源于stack exchange,提问作者Kürşat Soyarslan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:50:17