Python 为什么这段代码会产生缩进/语法错误
我正在尝试让用户输入8位条形码。如果代码长度不是8位,则会打印一条错误消息。如果长度为8位,则会引发错误Python 为什么这段代码会产生缩进/语法错误,python,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:
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
这里实际上发生了几个错误:
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()
您得到的语法错误是什么。请共享错误/堆栈跟踪。我在该函数后的下一行得到一个未指定的缩进。请确保粘贴缩进时缩进正确,因为此时您的
处于主执行级别,不在get_user\u input
函数中。UnboundLocalError:在赋值之前引用了局部变量“GTIN”,只是更新了它。如果您可以将其标记为解决方案,这将非常有帮助。谢谢,它可以工作,但是我如何使其继续,如果我输入的输入少于8,则会出现错误,但是如果我再次输入,则代码将继续单击向上投票和向下投票旁边的绿色勾号。此外,还更新了代码。