为什么此代码会产生缩进/语法错误

时间:2017-04-03 10:03:47

标签: python

我想让用户输入一个8位数的条形码。如果代码长度不是8位,则会输出错误消息。如果长度为8位,则会引发错误。

def get_user_input():
    global total_price
    """ get input from user """
while len(str(GTIN))!=8:
    try:
        GTIN = int(input("input your gtin-8 number:"))
        if len(str(GTIN))!=8:
            print("make sure the length of the barcode is 8")
        else:
            print("make sure you enter a valid number")
        return GTIN

1 个答案:

答案 0 :(得分:0)

这里实际上有几个错误:

  1. 您的缩进正在处理,因为while循环位于函数外部。 Python中的Witespace很重要。
  2. 每个try语句都需要有一个except。
  3. 此外,GTIN从未初步定义过,我修复过。
  4. 您的新代码:

    def get_user_input():
        global total_price
        """ get input from user """
        GTIN = ""
        while True:
            try:
                GTIN = int(input("input your gtin-8 number:"))
                if len(str(GTIN)) == 8:
                    break
                else:
                    print("make sure the length of the barcode is 8")
            except:
                pass
        return GTIN
    get_user_input()
    
相关问题