views:

393

answers:

5

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?

+10  A: 

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)]:
Prasoon Saurav
Oops! I was too late!
Prasoon Saurav
Oh noes! What do!
jleedev
@jleedev: Your post was not there when I was typing. So why a downvote?
Prasoon Saurav
Wasn't me. Here have an upvote.
jleedev
I would use a generator expression instead of a list comprehension there, were I to do it this way.
Ignacio Vazquez-Abrams
+4  A: 

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

Ignacio Vazquez-Abrams
+6  A: 

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)]:
jleedev
+2  A: 

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
mizipzor
+1  A: 
for (i,j) in zip(range(100), range(3, 100+3)):
Dyno Fu