Search code examples
pythonlistwhile-looprangemaxlength

How to use range() with while loop?


I need to create an empty list Ask the user for any input 5 times Only add the input to the list if it does NOT already exist

I keep getting into an infinity loop instead of only 5 times.

That's my code:

MyList = []
maxLengthList = range(5)
while len(MyList) < maxLengthList:
    i = input("Enter a number to the list: ")
    if i not in MyList:
        MyList.append(i)
print("That's your numbers list")
print(MyList)

Solution

  • The proper usage of range is:

    for x in range(start, end):
        print(x)
    

    So in your case it would be:

    # Using underscore here since you do not need the value for each loop
    for _ in range(5):
        i = input("Enter a number to the list: ")
        if i not in MyList:
            MyList.append(i)
    

    However, you could just set maxLengthList equal to 5 instead of range(5)