0

Convert to python:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    for (int i = 0, j = i + 3; i < 100; ++i, j= i+3)
         cout << i << " j: " << j << endl;

    getchar();
    return 0;
}

I try:

for i in range(99):
    j = i + 3
    print i, " j: ", j

How to make it one for loop?

6
  • I mean I want to make the python program only 2 lines like the C++ reall tis Commented Jan 29, 2010 at 8:10
  • 2
    Like 0ne python FOR LOOP to do the same job the C++ for l00p d03s Commented Jan 29, 2010 at 8:10
  • 4
    It already looks like one loop to me. How many do you see? Commented Jan 29, 2010 at 8:42
  • Wow, if this use-case was any more real world, it would be the actual REAL WORLD Commented Jan 29, 2010 at 8:46
  • The C++ is way more than two lines. And the idea that code is better because there are fewer lines is misguided. Commented Jan 29, 2010 at 8:55

6 Answers 6

8

Just change 99 to 100

for i in range(100):
  j = i + 3
  print i, " j: ", j

Or

for i,j in [(i, i+3) for i in range(100)]:
Sign up to request clarification or add additional context in comments.

2 Comments

@jleedev: Your post was not there when I was typing. So why a downvote?
I would use a generator expression instead of a list comprehension there, were I to do it this way.
6

These are identical except for the upper bound in the loop (98 vs 99). What is the question?

On one line (but please don't do this):

for i,j in [(i, i+3) for i in range(100)]:

Comments

5

Since j is always dependent on the value of i you may as well replace all instances of j with i + 3.

Comments

3

I dont get it, it is exactly one python for loop there. What is the question? Do you want the j declaration inside the loop declaration like in c++? Check Prasson'S answer for the closest python equivalent. But why have a j variable in the first place? j=i+3 seems to always be true, so why not this?

for i in range(100):
    print i, " j: ", i+3

Comments

1
for (i,j) in zip(range(100), range(3, 100+3)):

Comments

0
for i in range(100):
    j = i + 3
    print i, "j:", j
raw_input()

C++: http://ideone.com/7Kdmk

Python: http://ideone.com/nATEP

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.