简体   繁体   English

将用户输入附加到循环中的列表

[英]Appending user input to a list in a loop

I'm new to python programming and I'm doing some experiments with it. 我是python编程的新手,我正在做一些实验。 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. 希望我的问题不是太愚蠢:我正在编写一个小程序,它将输入添加到列表中,并在输入等于4时使用while循环打印它。 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)

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 : 问题是因为你有一次读取输入S = 1 ,例如,之后S总是1所以S永远不会是4而你的循环永远不会弯腰,你必须将你的输入加到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 don t need if statement in while`. 如果你确定S!= 4 in, whilet need if statement in

input() function returns string objects, so they can never be equal to 4 which is an int object. input()函数返回字符串对象,因此它们永远不能等于4,这是一个int对象。

To get out of the problem, replace 4 by '4' . 要解决问题,请将4替换为'4'

This will consider the '4' as a string as the equality will hold when you enter 4 as input 这会将'4'视为一个字符串,因为当输入4作为输入时,相等性将保持不变

There is another big problem with your code you don't update S anymore a more right answer would be: 您的代码还有另一个大问题,您不再更新S,更正确的答案是:

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 如果您不希望所有内容阻止等待新输入,那么您可能会考虑引入线程,但如果仅允许用户向数组添加值并通过添加4来停止这样做可能会有所帮助

You've created an infinite loop in your code. 您已在代码中创建了无限循环。 You're not changing the value of S after you enter the loop. 进入循环后,您不会更改S的值。 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 另外,代码中的if条件是无用的,因为它已经在while循环声明中设置了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM