Home > OS >  How can I loop a question until the list is complete
How can I loop a question until the list is complete

Time:12-06

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.

CodePudding user response:

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)

CodePudding user response:

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)
  • Related