[英]Why is my program only appending every other input into my list?
I am attempting to create a python program that takes multiple lines from the user and adds them to a list. 我正在尝试创建一个Python程序,该程序从用户那里获取多行并将其添加到列表中。 Inputting a blank line ends the program and returns the list.
输入空白行将结束程序并返回列表。 However only every other line is being added to the list.
但是,仅每隔一行添加到列表中。 If anyone could help that would be great.
如果有人可以帮助,那就太好了。
def read_lines():
lines = []
contin = True
while contin:
if len(input()) == 0:
contin = False
else:
lines.append(input())
return(lines)
There is my code here is what is happening: 这里是我的代码正在发生的事情:
>>> read_lines()
abc
def
ghi
jkl
['def', 'jkl']
Because you call it twice for each iteration. 因为您每次迭代都调用两次 。 You call it once for the
len
check, and once for the append
. 一次调用它进行
len
检查,一次调用append
。 Each time, it extracts a new string from the command line. 每次,它从命令行提取一个新的字符串。 Consider calling it once and storing the result in a variable, at the top of your loop.
考虑调用一次并将结果存储在循环顶部的变量中。 Then do your
len
and append
operations on that stored result. 然后对存储的结果执行
len
和append
操作。
The first time you call input
with the if
statement, it will get the input from the user. 第一次使用
if
语句调用input
时,它将从用户那里获得输入。 Suppose you enter a valid string, then the length will not be zero and the if
block will not be executed. 假设您输入一个有效的字符串,那么长度将不会为零,并且
if
块将不会执行。 So, you go to else
block where you again get a new input from the user; 因此,您可以转到
else
块,再次从用户那里获得新的输入。 This discards the previous input that you got since you did not store it in any variable. 由于您没有将其存储在任何变量中,因此这将丢弃您之前获得的输入。 Thus, for each valid input you give only the alternate elements are appended to the list.
因此,对于每个有效的输入,您只将替代元素添加到列表中。
Your code will append all the input you enter into the list when you alternately press enter
key and a valid input in the same order. 当您按
enter
键和相同顺序的有效输入时,您的代码会将您输入的所有输入追加到列表中。
I have added the correct code here: 我在这里添加了正确的代码:
def read_lines():
lines = []
contin = True
while contin:
string = input()
if len(string) == 0:
contin = False
else:
lines.append(string)
return(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.