Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested For loops  RSS feed

 
David Clark
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I browsed thru some books on Python at Barnes & Noble this morning. I noticed that the syntax for the For loop is different from other languages. One needs to have an ordered list.

Here's an example from a Java demo that I have:

for (intI = 0, intJ = 0;
     intI * intJ < 10000;
     intI++, intJ += 2)
    System.out.println(intI + " * " + intJ + " = " + intI * intJ);

There are 2 integer variables. Both are initialized in the For loop.

(For some reason, my text isn't tabbing in the preview!)

I'm guessing that in Python I'd have to have nested For loops. I'd have to have one For loop for the I variable & one For loop for the J variable. Is my assumption correct?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, let's add this topic to the Java forums -- as you are asking a question regarding the Java for loop.

Henry
 
David Clark
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, I'm asking about Python For loops.

I used a Java For loop as an example. I'm wondering how that example would be done in Python.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

David Clark wrote:
I'm guessing that in Python I'd have to have nested For loops. I'd have to have one For loop for the I variable & one For loop for the J variable. Is my assumption correct?


Well... no. That Java example loop does a single loop, while modifying both variables at the same time. A nested loop would iterate through both variables differently.

I would guess a much better conversion is to use a python while loop -- with the initialization code before the while loop, and with the reinitialization code as the last lines of the while loop block.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!