为什么这段代码不能让我检查输入无效

时间:2016-11-29 22:19:37

标签: python-3.x

这不是整个代码,而是我正在试验的代码,以获得整个代码的解决方案。我还需要一个处理无效字符串输入的答案。

    def menu_payment():
burger_count= (input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
if (burger_count !=int) or (burger_count<=0):
    print("You must eneter a positive whole number for your order. Please try again.")
    menu_payment()

3 个答案:

答案 0 :(得分:0)

检查有效字符串的问题来自if语句。我建议首先检查值是否为int,然后检查它的值。这是解决该问题最简单,最容易混淆的方法。

答案 1 :(得分:0)

输入将始终将用户输入转换为字符串。因此,输入&#34; 1&#34;是&#34; 1&#34;的字符串,而不是整数。

您可以尝试使用int函数包装输入,如:

burger_count = int(input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))

但是,如果输入除整数之外的任何内容,则会抛出ValueError。

另外,我不认为检查变量类型就是这样。你可以这样做:

if type(burger_count) is not int:
    <do something>

可能超级低效(咖啡前的脚本编写很糟糕)但是我会如何处理这个问题:

def menu_payment():
    while True:
        try:
            burger_count = int(input("burgers: "))
        except ValueError:
            print("You must eneter a number for your order. Please try again.")
            continue
        else:
            if burger_count <= 0:
                print("You must eneter a number for your order. Please try again.")
                continue
            else:
                return burger_count

答案 2 :(得分:0)

尝试这样做:

def menu_payment():
    burger_count = input("How many burgers would you like:")
    try:
        burger_count = int(burger_count)
        valid_number = 1
    except:
        print(burger_count, " is not a valid number")
        valid_number = 0
    if valid_number == 1 and burger_count > 0:
        print ("I will get your burgers right away")
    else: 
        print("Please put a valid number and no negetives")