如果是len声明

时间:2016-06-23 08:17:55

标签: python if-statement variable-length-array

我输入七位数字就可以计算出gtin-8产品代码。但是如果我输入的数字超过7位,那么if len语句是为了识别我输入的数字超过7位,但事实并非如此。我试着将它放入一个变量,但这也不起作用...任何帮助将不胜感激!这是我的代码........

gtin1 = int(input("Enter your first digit... "))
gtin2 = int(input("Enter your second digit... "))
gtin3 = int(input("Enter your third digit... "))
gtin4 = int(input("Enter your fourth digit... "))
gtin5 = int(input("Enter your fifth digit... "))
gtin6 = int(input("Enter your sixth digit... "))
gtin7 = int(input("Enter your seventh digit... "))

gtin_join = (gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7) 

if len(gtin_join) == 7:

3 个答案:

答案 0 :(得分:1)

你可能想做的事情是这样的(注意我在这里使用了一个列表):

ls = []
while len(ls) < 7:
    try: #always check the input
        num = int(input("Enter your {0} digit:".format(len(ls)+1) ))
        ls.append(num)
    except: 
        print("Input couldn't be converted!")

print(ls) #ls now has 7 elements

您创建的元组的长度始终为7,因此if - 语句的结果始终为True

有关列表和元组之间的区别,请参阅此问题here

答案 1 :(得分:-1)

你的gtin_join是元组,如果你想要列表,你应该使用方括号。您可以使用此示例测试变量类型:

gtin1 = int(input("Enter your first digit... "))
gtin2 = int(input("Enter your second digit... "))
gtin3 = int(input("Enter your third digit... "))
gtin4 = int(input("Enter your fourth digit... "))
gtin5 = int(input("Enter your fifth digit... "))
gtin6 = int(input("Enter your sixth digit... "))
gtin7 = int(input("Enter your seventh digit... "))

gtin_join = (gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7)

print(type(gtin_join))

gtin_join = [gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7]

print(type(gtin_join))

if len(gtin_join) == 7:
    print 7

答案 2 :(得分:-1)

我会做以下事情:

gtin_list = []
while len(gtin_list) != 7:
    gtin = input("Please enter all 7 digits separated by commas...")
    gtin_list = [int(x) for x in gtin.split(",")]