rajathans
rajathans

Reputation: 197

Taking space separated input in loop with python

I'm still learning python, so this may seem silly. This is the C++ code i want the python equivalent of:

int t;
for(int i=0;i<n;i++)
{
    cin>>t;
    ans = do_something(t);
}
cout<<ans;

I can do this by making t a list and then using each element as do_something's parameter, but i want a solution similar to the C++ code. Also input t is taken space separated. Eg

1 2 3 4 5
ans

`

Upvotes: 0

Views: 2646

Answers (1)

ZdaR
ZdaR

Reputation: 22964

input_from_user = raw_input() #which is a string '1 2 3 4 5'
numbers = input_from_user.split()
>>> ['1', '2', '3', '4', '5']
numbers = map(int, numbers) #To convert the string elements to integers.
>>> [1, 2, 3, 4, 5]

for i in numbers:
    ans = do_something(i)
print ans

Or you can do this thing in single line as :

for i in map(int,raw_input().split()):
    ans = do_something(i)
print ans

Upvotes: 2

Related Questions