-2

I have a simple script which asks the user for their meal price and adds tax to it. my question is, how can I make it so the user can input "yes" and "no" instead of an integer like 0 or 1?

Here is the code:

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.")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user52157
  • 3
  • 3
  • 2
    A few notes for your question: you can leave off the "first post", "lols" and other fluff. I know you're just being friendly, but you'll get better answers if you focus on making your question easy to read. For example, your post wasn't indented properly, so none of your code had syntax highlighting. Next, you should post the code you're actually using. This code won't run because you have typos in it that would cause NameError exceptions. Lastly, check for duplicates before you post a question. As jonrsharpe hinted, 2 minutes with google would get you a ton of examples of string comparisons. – skrrgwasme Aug 14 '14 at 22:29
  • @g.d.d.c - I don't see how the linked question is relevant at all - maybe to the overall task they are trying to achieve but they ask a specific question which cdonts answers. – neil Aug 14 '14 at 22:32

1 Answers1

1

You can use this function:

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

Which works like this:

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

Hope this helps.

cdonts
  • 9,304
  • 4
  • 46
  • 72
  • It's probably much clearer to write `if s not in ("yes", "no"): return None; return s == "yes"` rather than implicitly returning `None` – sapi Aug 16 '14 at 04:34