Member-only story
From Python To Java (Part 3) — For Loops & While Loops
This series of articles is written for those of you who are somewhat comfortable in Python, and are looking to pick up some Java. In this article, we’ll run through the difference in for loops, for-each loops and while loops in Python and Java.
For Loops
Python
for i in range(5):
print(i)
This prints the numbers 0, 1, 2, 3 & 4.
Java
for (int i=0; i<5; i++) {
System.out.println(i);
}
Here is the equivalent in Java — this will too print the numbers 0, 1, 2, 3 & 4. Notice that we no longer have a range
function, but instead have 3 separate statements in a set of brackets. The leftmost statement defines our start
(which is 0), the middle statement defines our end
(which is 5, exclusive of 5), and the rightmost statement defines our step
(which is 1). In Java, i++
is simply another way of incrementing i
by 1, and is the same as i+=1
.
For-each Loops
Python
Let’s say we have a list of strings, and we wish to iterate through it.
lis = ["apple", "orange", "pear"]for fruit in lis:
print(fruit)