Search code examples
pythonif-statementvariable-length-array

If len Statement


I type in seven digits to be able to work out a gtin-8 product code. But if I type in more than seven digits, the if len statement is meant to recognise that I have typed in more than seven digits, but it doesn't. I tried putting this into an variable but that did not work either... Any help would be appreciated!!! This is my code........

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:

Solution

  • What you probably want to do is something like that (notice that I'm using a list here):

    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
    

    Your created tuple always has a length of 7 so your if-statement always turns out to be True.

    For the difference between list and tuple please see this question here.