Home > front end >  why is there no elements getting inserted and loop goes infinite?
why is there no elements getting inserted and loop goes infinite?

Time:04-10

i am trying to get elements of list that must be string,unique and have less than 5 char but no matter what i enter as input no value is getting appended though it meets all criteria.

lst=[]
n=int(input("Enter number of elements:"))
while len(lst)<=n:
    print("Enter element:")
    a=input()
    if a is str and len(a)<5 and a not in lst:
        lst.append(a)
    else:
        print("Element must be string,unique and have less than 5 characters")
print(lst)

CodePudding user response:

a is str will always be False because a is an instance of the type str. You'd use isinstance(a, str) to check if a was a string instance -- in this case however it's not needed because input() always returns a string (unless you're using a very old version of Python, in which case you can use raw_input instead of input to get the modern behavior).

lst = []
n = int(input("Enter number of elements:"))
while len(lst) < n:
    a = input("Enter element:\n")
    if len(a) < 5 and a not in lst:
        lst.append(a)
    else:
        print("Element must be unique and have fewer than 5 characters")

print(lst)

Note that you want your loop to be on len(lst) < n (not <= n) since the body of the loop will append an item after you've done that check.

CodePudding user response:

short answer: use type(a) is str.

long answer: built-in method input by default return string so type(a)==str always true. a is str always false because is operand compare if two variables point to the same (identical) objec.

full code:

lst=[]
n=int(input("Enter number of elements:"))
while len(lst)<n:
    print("Enter element:")
    a=input()
    if len(a) < 5 and a not in lst:
        lst.append(a)
    else:
        print("Element must be string,unique and have less than 5 characters")
print(lst)
  • Related