for Loops
Python |
Java |
There is just one type
of for loop, which visits each element in an iterable
object, such as a string or list. Form: for
<variable> in <iterable>: <statement> É <statement> Example: for s in
aListOfStrings: print(s)
The variable picks up
the value of each element in the iterable object and is visible in the loop
body. The statements in the loop body are marked by indentation.
Simple count-controlled loops that iterate through a range of integers have three forms:
<statement> É <statement>
for <variable> in range(<lower bound>, <upper bound>):
<statement> É <statement>
for <variable> in range(<lower bound>, <upper bound>, <step value>):
<statement> É <statement> |
There are two types, a
loop for visiting each element in an iterable object, and a loop with the
same behavior as a while loop. Form of the first type
(also called an enhanced for loop): for
(<type> <variable> : <iterable>){ <statement> É <statement> } Example: for (String s :
aListOfStrings){ System.out.println(s); } The variable picks up
the value of each element in the iterable object and is visible in the loop
body. The statements in the
loop body are marked by curly braces ({}).
When there is just one statement in the loop body, the braces may be
omitted. Form of the second type: for
(<initializer>; <continuation>; <update>){ <statement> É <statement> } Example: for (int i = 1;
i <= 10; i++){ System.out.println(i); } This loop has the same
behavior as the following while loop: int i = 1; while (i <=
10){ System.out.println(i); i++; } |