7

I am a python beginner. I am trying to accept inputs from the user as long as he/she wishes. The program should stop accepting inputs when the enter key alone is pressed.

That is

25
65
69
32 
   #stop here since the enter key was pressed without any input

I came up with the following code of doing that....

a = []
while 1:

    b = input("->")
    if(len(b)>0):
        a.append(b)
    else:
        break

  1. Is there any other efficient 'pythonic' ways of doing this ?

  2. While this works perfectly with python 3.3 it doesnt work with python 2.7 (with input() replaced by the raw_input() function). The screen just stays dumb without any response. Why is that?

  3. Is there any inbuilt function with which i can convert strings back to integers!?

Jon
  • 11,356
  • 5
  • 40
  • 74
Ray
  • 293
  • 1
  • 3
  • 12
  • No need for parenthesis around the if statement, use `int('string')` to change a string to an integer – samrap Dec 11 '13 at 05:28
  • Please watch out with whitespaces in Python. I realized that your code example mixes tabs and common spaces. – Jon Dec 11 '13 at 08:05

4 Answers4

8

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).

DSM
  • 342,061
  • 65
  • 592
  • 494
7

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)
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • Using a lot of functions doesn't make anything "functional" or "functional style" (in the sense of the functional paradigm). Functinal programming using iteration instead of recursion is quite ... interesting – Hyperboreus Dec 12 '13 at 02:21
  • IT is still "functional" in the sense that it uses functions to wrap functionality and iterate of the results. Wrapping the side-effect producing ``input()`` function. – James Mills Dec 12 '13 at 02:22
  • It's certainly not strictly pure functional however :) – James Mills Dec 12 '13 at 02:23
  • Also bear in mind that the built-in `iter` takes a sentinel argument and does the same thing as your generator. So it boils down to `[int(x) for x in iter(lambda: input('-> '), '')]`. – Hyperboreus Dec 12 '13 at 02:34
  • Well yeah. But that's probably going a bit too far right? :) I mean a line-liner? :) – James Mills Dec 12 '13 at 02:42
1
  1. idk, this code looks good for me.
  2. it works perfectly on my python 2.7.5, with raw_input()
  3. just use int() function: for example, int('121') returns 121 as integer
Twisted Meadow
  • 443
  • 2
  • 7
0

As a matter of code style, I always prefer loops without breaks. In my humble opinion the most human readable version would then be (Python 3):

a=[]
for line in iter(input, ''):
    a.append(line)
Marcel Sonderegger
  • 772
  • 1
  • 8
  • 21