使用“是”和“否”作为输入变量响应

-2 投票
1 回答
721 浏览
提问于 2025-04-18 17:20

我有一个简单的脚本,它会询问用户他们的餐费,并在此基础上加上税。我想知道,怎么才能让用户输入 "yes""no",而不是像 01 这样的数字呢?

以下是代码:

a = input("what is the price of your meal?") #self explanatory
print (float(a) * 0.08) #calculates tax
print ("Is the price of your tax")  #prints tax
b = input("do you want me to add the tax to your total meal price? press 0 for yes and 1 for no") #asks user if they would like to have tax added to the meal price
if b == str(0): #yes they want tax added
    print ("The price of your meal is...") 
    print ((float(a) * 0.08) + float(a)) #adds tax and initial meal price together
elif b == str(1): #no they do not
    print ("Your loss.")
else: #if they did not choose 0 or 1
    print ("I asked for 0 or 1")
c = input("will that be all? 0 for yes 1 for no")
if c == str(0):
    print ("thank you for coming!")
elif c == str(1):
    print ("what else do you need?")
else:
    print ("this is a yes or no question")

d = imput("Let me repeat this, what else do you need?")
if d == str(nothing):
    print ("begone then")
elif d == str(you):
    print ("yuck...")
else:
    print ("You either want nothing, or me. choose.")

1 个回答

1

你可以使用这个函数:

def yesno_to_bool(s):
    s = s.lower()
    if s == "yes":
        return True
    elif s == "no":
        return False

它的工作原理是这样的:

>>> yesno_to_bool("yes")
True
>>> yesno_to_bool("no")
False
>>> yesno_to_bool("something is not yes or no")
None

希望这对你有帮助。

撰写回答