如果用户输入字符串而不是整数,如何使代码重新运行

时间:2019-02-16 22:26:13

标签: python validation syntax

如果用户在“您想要多少?(1-10)>”处输入字符串,我希望重新运行try语句,而不是获取NameError来获取正确的整数输入。

我必须使用try / except语句进行大学作业

这个问题有所不同,因为我无法将其格式化为管理员指定的链接,我必须遵守教授要求的语法。

cont = str("y") 
item_cnt = 0          # running count of number of items ordered
order_total = 0.0     # accumulate total dollars
price = 3.5           # all cookies rae $3.50 per box

# banner
print("Thank you for placing your order")
cust = input("please enter your name> ")

# validate data entry

while cont.lower() == "y":

    valid_data = False 

    # input and data validation

    while not valid_data: 
        # display cookie list
        print("please choose a flavor:")
        print("num\tflavor")
        print("1.\tSavannah")
        print("2.\tThin Mints")
        print("3.\tTagalongs")
        print()

        item = input("enter item number> ")

        if item == "1" or item == "2" or item == "3":
            valid_data = True
        else:
            print("That was not a valid choice, please try again")

    valid_data = False # reset boolean flag

    while not valid_data:


        try:
            qty = int(input("How many would you like? (1-10)> "))
        except Exception as detail:
            print("Error: ", detail)
        else:
            if qty >= 1 and qty <= 10:
                valid_data = True



        # determine totals
        item_total = qty * price

        # determine cookie name for output display
        if item == 1:
            name = "Savannah"
        elif item == 2:
            name = "Thin Mints"
        else:
            name = "Tagalongs"


    # verify inclusion of this item
    valid_data = False

    while not valid_data:

        incl = input("would you like to add this to your order (y/n)> ")
        print()

        if incl.lower() == "y":
            order_total = order_total + item_total
            item_cnt = item_cnt + 1
            valid_data = True
            print ("{} was added to your order".format(name))
        elif incl.lower() == "n":
            print("{} was not added to your order".format(name))
            valid_data = True
        else:
            print("that was not a valid response, please try again")



    cont = input("\nwould you like to add another? (y/n)> ")




print("order for {}".format(cust))
print("Total Items = {}".format(item_cnt))
print("Total Boxes = {}".format(qty))
print("Total Cost = ${}".format(item_total))
print()
print("Thank you for your order")       

我希望“您想要多少?(1-10)>” try语句重新运行,直到代码收到正确的整数为止。

我似乎通过在ValueError之后添加继续来解决了该问题

while not valid_data:
        try:
            qty = int(input("How many would you like? (1-10)> "))
        except ValueError as detail:
            print("Error: ", detail)
            continue
        except Exception as detail:
            print("Error: ", detail)
        else:
            if qty >= 1 and qty <= 10:
                valid_data = True

1 个答案:

答案 0 :(得分:0)

只需移动此代码:

# determine totals
item_total = qty * price

# determine cookie name for output display
if item == 1:
    name = "Savannah"
elif item == 2:
    name = "Thin Mints"
else:
    name = "Tagalongs"

最里面的while块之外。看来您的代码无法正常工作的唯一原因是此行位于“ while”循环中:

item_total = qty * price
如果抛出异常,则不会将

定义为'qty'。如果用户输入非数字,您会在这里出现异常,对吧?也没有理由将下面的内容放入循环中,因为如果由于输入错误而要循环,那对您没有任何好处。

一件有趣的事...如果您首先输入数字<1或> 10,然后输入字母或其他字母,则您的代码将起作用,因为'qty'将具有一个值。