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

