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
相关产品推荐
相关产品推荐

