tags:

views:

117

answers:

2

Hey this is a really quick question. I guess I'll give correct answer in less than 2 minutes after posting this question.

I've started learning python, like 5 minutes ago, so mind the stupidity of the question. To test it I'm re-writing some algorithms i had.

Could someone tell me how can I read N ints from the input, and stop reading when I find the \n ? Also adding them to an array that I can work with?

something like this from C but in python

while(scanf("%d%c",&somearray[i],&c)!=EOF){
    i++;
    if (c == '\n'){
        break;
    }
}
+4  A: 
lst = map(int, raw_input().split())

raw_input() reads a whole line from the input (stopping at the \n) as a string. .split() creates a list of strings by splitting the input into words. map(int, ...) creates integers from those words.

Roberto Bonvallet
+7  A: 

There is no direct equivalent of scanf in Python, but this should work

somearray = map(int, raw_input().split())

In Python3 raw_input has been renamed to input

somearray = map(int, input().split())

Here is a breakdown/explanation

>>> raw=raw_input()              # raw_input waits for some input
1 2 3 4 5                        # I entered this
>>> print raw
1 2 3 4 5                            
>>> print raw.split()            # Make a list by splitting raw at whitespace
['1', '2', '3', '4', '5']            
>>> print map(int, raw.split())  # map calls each int() for each item in the list
[1, 2, 3, 4, 5]
gnibbler