Why is my program only appending every other input into my list?

时间:2016-10-20 19:01:44

标签: python list

I am attempting to create a python program that takes multiple lines from the user and adds them to a list. 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']

2 个答案:

答案 0 :(得分:3)

Because you call it twice for each iteration. You call it once for the len check, and once for the 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.

答案 1 :(得分:0)

The first time you call input with the if statement, it will get the input from the user. Suppose you enter a valid string, then the length will not be zero and the if block will not be executed. So, you go to else block where you again get a new input from the user; 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.

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)