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

时间:2014-08-14 22:19:52

标签: python python-3.x

我有一个简单的脚本,询问用户的用餐价格并增加税收。我的问题是,我该如何制作,以便用户可以输入"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 个答案:

答案 0 :(得分: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

希望这有帮助。