0

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

`

2
  • for loop, raw_input and print show do the job, You should learn python first, - docs.python.org/2.7/contents.html Commented Feb 15, 2015 at 5:39
  • what is the do_somthing() doing? Commented Feb 15, 2015 at 5:43

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.