How can I loop a question until the list is complete

Question:

enter code hereHow can I loop a question to fill up a list? I need user to input five numbers. Everytime user inputs a number I append the number into a list. My problem is, the code doesn’t loop, so it only takes one input from user and the code stops.

here’s the extract of my code:

    def funct1():
        for i in range(5):
            user = int(input('Enter a Number: '))
            userList.append(user)
            return userList
        
    userList = []   
    Sum_Num()
    print(userList)
        

I tried doing

for l in range(5) and while True but none worked.

Asked By: astra

||

Answers:

you should really provide a minimally reproducible code example, but I would assume you are having an indent error. This snippet should be what you are looking for:

values = []
for i in range(5):
    values.append(input())
print(values)

Edit: After you posted your relevant code, I can see that you do have an indent error. The return statement needs to exist outside of the for loop.

    def funct1():
        for i in range(5):
            user = int(input('Enter a Number: '))
            userList.append(user)
        return userList
        
    userList = funct1()   
    print(userList)
Answered By: Justin Smith

Try this:

def funct1():
    userList = []
    while len(userList) < 5:  # Keep looping until the list has 5 numbers
        user = int(input('Enter a Number: '))
        userList.append(user)

    return userList

userList = funct1()
print(userList)
Answered By: Nickpick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.