我将如何使用' if else'为每个单独的输入创建例外的语句?

时间:2017-09-30 23:23:07

标签: python python-3.x conditional

print("----------Paint Mmatching Pricer Program!----------")
everydaypaint = 19.99
selectpaint = 24.99
premiumpaint = 32.99
matchingprice = 4.99

quality = str(input("What quality of paint do you need [Everyday, Select, or Premium]?"))
colormatch = str(input("Will you need colormatching [y/n]?"))
if quality == 'everyday' or quality == 'Everyday':
    if colormatch == 'y' or colormatch == 'Y':
        total = everydaypaint + matchingprice
        print("Total price of %s paint with color matching is $%.2f per gallon" % (quality, total))
    elif colormatch == 'n' or colormatch =='N':
        total = everydaypaint
        print("Total price of %s paint with out color matching is $%.2f per gallon" % (quality, total))
elif quality == 'select' or quality == 'Select':
    if colormatch == 'y' or colormatch == 'Y':
        total = selectpaint + matchingprice
        print("Total price of %s paint with color matching is $%.2f per gallon" % (quality, total))
    elif colormatch == 'n' or colormatch =='N':
        total = selectpaint
        print("Total price of %s paint with out color matching is $%.2f per gallon" % (quality, total))
elif quality == 'premium' or quality == 'Premiumy':
    if colormatch == 'y' or colormatch == 'Y':
        total = premiumpaint + matchingprice
        print("Total price of %s paint with color matching is $%.2f per gallon" % (quality, total))
    elif colormatch == 'n' or colormatch =='N':
        total = premiumpaint
        print("Total price of %s paint with out color matching is $%.2f per gallon" % (quality, total))

我需要使用else语句为quality和colormatch变量创建异常!例如,当提示用户输入无效输入时,每个人都需要返回异常。质量其他声明应返回"必须每天进入,选择或溢价"并且colormatch变量应返回"必须输入y或n"。

2 个答案:

答案 0 :(得分:0)

也许不是使用" else",而是考虑使用"而#34;循环继续问同样的问题,直到他们提供预期的答案。这是质量的一个例子,你可以推断它也可以用于颜色匹配。这将使用户保持循环,直到他们提供正确的答案:

quality_question = "What quality of paint do you need [Everyday, Select, or Premium]?"

selected_quality = input(quality_question)

while selected_quality.lower() not in ['everyday', 'select', 'premium']:

        selected_quality = input(quality_question)

答案 1 :(得分:0)

shift中,您可以编写处理所选异常的程序。例如:

while True:
    try:
        inp = input('Enter value: ')
        if inp == 'fooBar': break

    except Exception as exp:
        print(exp) #shows Error
        print('Invalid input')

通常,当您要求输入用户时,您希望将其嵌套在a中 “while”循环和try / except语句。正如马克西姆所说,你想提供用户输入,直到他们给出预期的结果。如果用户未输入预期结果,则抛出异常,从而让用户知道您输入的内容不是为了获得脚本的最终结果。