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

Python中while循环异常:输入无效tip_val后持续输出else语句

问题分析与解决

你的问题核心是输入验证逻辑的顺序错误:当前代码中tip_val的输入仅在while循环执行前运行一次,若初始输入的数值不在允许的(10,12,15)范围内,循环会一直重复检查同一个无效值,导致无限输出错误提示,却没有让用户重新输入的机会。

修正后的代码

把tip_val的输入逻辑移到while循环内部,确保每次验证失败后,用户都能重新输入有效数值:

def tip():
    print("Welcome to the tip calculator")
    bill = float(input("what is the total bill :"))
    ppl = int(input("how many people split the bill :"))  # 修正拼写错误:mny→many,spilt→split

    while True:
        tip_val = int(input("what percentage of tip you would like to give i.e 10 or 12 or 15 :"))
        if tip_val in (10, 12, 15):
            break
        else:
            print("invalid choice,please enter the valid tip percentage from 10/12/15 ")
    
    disc_amount = (tip_val * bill) / 100
    total_amount = disc_amount + bill
    amount_per_prsn = total_amount / ppl
    print(f"discount amount is :{disc_amount}")
    print(f"total amount is :{total_amount}")
    print(f"each person pays :{amount_per_prsn}")

tip()

另一种可选写法

如果想保留初始输入的提示样式,也可以在else分支中重新获取输入:

def tip():
    print("Welcome to the tip calculator")
    bill = float(input("what is the total bill :"))
    ppl = int(input("how many people split the bill :"))
    tip_val = int(input("what percentage of tip you would like to give i.e 10 or 12 or 15 :"))

    while True:
        if tip_val in (10, 12, 15):
            break
        else:
            print("invalid choice,please enter the valid tip percentage from 10/12/15 ")
            tip_val = int(input("Enter tip percentage again: "))  # 重新获取输入
    
    disc_amount = (tip_val * bill) / 100
    total_amount = disc_amount + bill
    amount_per_prsn = total_amount / ppl
    print(f"discount amount is :{disc_amount}")
    print(f"total amount is :{total_amount}")
    print(f"each person pays :{amount_per_prsn}")

tip()

注:顺便修正了原代码中的两处拼写错误,让提示文本更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:53:18