简体   繁体   English

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

[英]Why does this code produce an indent/syntax error

I am trying to have the user enter an 8 digit barcode. 我正在尝试让用户输入8位条形码。 If the code is not 8 digits long, it prints an error message. 如果代码不是8位数字长,则会显示一条错误消息。 If it is 8 digits long, it raises an error. 如果它是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

There actually several errors going on here: 实际上,这里发生了几个错误:

  1. Your indentation was being processed as the while loop being outside the function. 您的缩进正在作为while循环在函数外部进行处理。 Witespace in Python matters. Python中的Witespace很重要。
  2. It is required to have an except with every try statement. 每个try语句都必须有一个except。
  3. Additionally, GTIN was never initially defined, I fixed that. 此外,GTIN最初从未定义,我已修复该问题。

Your new code: 您的新代码:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM