Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting input till newline in python

Tags:

python

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!?

like image 953
Ray Avatar asked Dec 11 '13 05:12

Ray


1 Answers

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)
like image 110
James Mills Avatar answered Oct 06 '22 00:10

James Mills