Appending user input to a list in a loop

18,808

Solution 1

You've created an infinite loop in your code. You're not changing the value of S after you enter the loop. You should add get an another input from inside the loop like so:

S=input()
L=[]
while S!=4:
   L.append(S)
   S = input()
print(L)

In addition, The if condition in your code is useless since It's already set in the while loop declaration

Solution 2

There is another big problem with your code you don't update S anymore a more right answer would be:

S=input()
L=[]
while S!=4:
    L.append(S)
    if S=="4":
        break
    S = input()
print(L)

If you'd not want everything to block waiting for new input then you might consider throwing in threading but if it's just to allow the user to add values to an array and stop doing that by adding 4 this could help

Solution 3

The problem is because you one time read the input S = 1 for example, after that S always 1 so S never be 4 and your loop is never stoop, you must add your input to while:

list = []
number = -1
while number != 4:
    number = int(input())
    list.append(number)
print(list)

And if you check that S != 4 in while you dont needifstatement inwhile`.

Solution 4

input() function returns string objects, so they can never be equal to 4 which is an int object.

To get out of the problem, replace 4 by '4'.

This will consider the '4' as a string as the equality will hold when you enter 4 as input

Share:
18,808
Franz
Author by

Franz

Updated on July 30, 2022

Comments

  • Franz
    Franz over 1 year

    I'm new to python programming and I'm doing some experiments with it. Hoping my question is not too silly: I'm writing a little program that adds inputs to a list and print it when the input equals to 4, using a while loop. the problem is it never stops to add inputs and print the list. My code is:

    S=input()
    L=[]
    while S!=4:
        L.append(S)
        if S==4:
            break
    print(L)