我正在学习Python并尝试使用while循环,但是如果输入无效的tip_val,则会连续获得else打印语句
def tip():
print("Welcome to the tip calculator")
bill = float(input("what is the total bill :"))
ppl = int(input("how mny people spilt 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 discount 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 got :{amount_per_prsn}")
tip()
您需要在循环中内部重新定义值,否则它只是一遍又一遍地检查相同的值:
def tip():
print("Welcome to the tip calculator")
bill = float(input("what is the total bill :"))
ppl = int(input("how mny people spilt the bill :"))
# move the tip calculation down here
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
print("invalid choice,please enter the valid discount 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 got :{amount_per_prsn}")