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

问题描述 投票:-2回答:1

这个问题在这里已有答案:

如果用户输入一个字符串“你想要多少?(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之后添加一个continue来解决问题

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
python validation syntax
1个回答
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'循环中:

item_total = qty * price

如果您抛出异常,则不会定义'qty'。如果用户输入非号码,你在这里得到例外,对吗?也没有理由在循环中使用下面的东西,因为如果你因为输入错误而要循环,这对你没有任何好处。

一个有趣的事情......如果你首先输入一个数字<1或> 10,那么输入字母或其他什么,你的代码就可以了,因为'qty'会有一个值。

© www.soinside.com 2019 - 2024. All rights reserved.