Accepting input till newline in python

Solution 1:

Your approach is mostly fine. You could write it like this:

a = []
prompt = "-> "
line = input(prompt)

while line:
    a.append(int(line))
    line = input(prompt)

print(a)

NB: I have not included any error handling.

As to your other question(s):

  1. raw_input() should work similarly in Python 2.7
  2. int() -- Coerves the given argument to an integer. It will fail with a TypeError if it can't.

For a Python 2.x version just swap input() for raw_input().

Just for the sake of education purposes, you could also write it in a Functional Style like this:

def read_input(prompt):
    x = input(prompt)
    while x:
        yield x
        x = input(prompt)


xs = list(map(int, read_input("-> ")))
print(xs)

Solution 2:

Probably the slickest way that I know (with no error handling, unfortunately, which is why you don't see it too often in production):

>>> lines = list(iter(input, ''))
abc
def
.
g

>>> lines
['abc', 'def', '.', 'g']

This uses the two-parameter call signature for iter, which calls the first argument (input) until it returns the second argument (here '', the empty string).

Your way's not too bad, although it's more often seen under the variation

a = []
while True:
    b = input("->")
    if not b:
        break
    a.append(b)

Actually, use of break and continue is one of the rare cases where many people do a one-line if, e.g.

a = []
while True:
    b = input("->")
    if not b: break
    a.append(b)

although this is Officially Frowned Upon(tm).