ValueError的问题

时间:2014-05-20 04:21:37

标签: python python-3.x

def Amount_of_pizzas():
    global numPizza
    numPizza = int(input("Enter the number of pizzas wanted (max 5)"))
    return numPizza

Amount_of_pizzas()
Num_of_pizzas_boolean = True
while Num_of_pizzas_boolean:
    try:
        if numPizza > 5 or numPizza < 1:
            print("You can not order less than 1 pizza or more than 5 restarting in 3 seconds")
            time.sleep(3)
            Amount_of_pizzas()
            continue
    except ValueError:
        print("not a number/appropriate number")
        Amount_of_pizzas()
        continue

结果:

numPizza = int(input("Enter the number of pizzas wanted (max 5)"))
ValueError: invalid literal for int() with base 10: '**a string input**'

当我尝试输入str值来搞砸

1 个答案:

答案 0 :(得分:0)

您需要检查某人是否输入了不是数字的内容:

def amount_of_pizzas():
    # global numPizza - you don't need this since you are returning it
    num_pizza = input("Enter the number of pizzas wanted (max 5)")
    try:
        num_pizza = int(num_pizza)
    except ValueError:
        print('Please enter a number, not a string')
        amount_of_pizzas() # Go through the loop again
    if num_pizza > 5:
        print('You can have no more than 5 pizzas')
        amount_of_pizzas()
    # Only return if all checks have passed
    return num_pizza

你还应该检查是否有人输入0或-5作为输入,但我会把它留给你。