Java gives you two for loops: the classic counting one, for (int i = 0; i < n; i++), and the enhanced one, for (String doc : docs). Python keeps only the second. Every Python for loop walks over items.
That sounds limiting until you meet three tiny built-ins: range, enumerate and zip. Together they replace every counting loop you’ve written, with less code and fewer off-by-one bugs.
This is part 3 of Python for Java Developers. Part 2 covered variables, None and truthiness, which you’ll need for conditions below.
if, elif, else
Same logic as Java, minus the brackets and braces:
if (score > 0.8) {
label = "high";
} else if (score > 0.5) {
label = "medium";
} else {
label = "low";
}if score > 0.8:
label = "high"
elif score > 0.5:
label = "medium"
else:
label = "low"Three changes: no parentheses around the condition, a colon at the end of each line, and else if becomes elif. The indented lines are the block.
Two extras Java doesn’t have:
if 0 <= temperature <= 1: # comparisons chain
...
if model in ("small", "medium"): # membership test instead of a chain of ||
...
The for loop walks over items
for (String doc : docs) {
System.out.println(doc);
}for doc in docs:
print(doc)It works on anything you can iterate: lists, strings (character by character), dict keys, files (line by line), and more.
range: when you need numbers
range produces numbers on demand. The stop value is never included, like i < n in Java:
| Java | Python | Gives |
|---|---|---|
for (int i = 0; i < 5; i++) |
for i in range(5): |
0, 1, 2, 3, 4 |
for (int i = 1; i <= 10; i++) |
for i in range(1, 11): |
1 to 10 |
for (int i = 0; i < 10; i += 2) |
for i in range(0, 10, 2): |
0, 2, 4, 6, 8 |
for (int i = 9; i >= 0; i--) |
for i in range(9, -1, -1): |
9 down to 0 |
for (int i = 0; i < list.size(); i++) |
usually enumerate, below |
range doesn’t build a list in memory. range(1_000_000) costs almost nothing. (Yes, underscores in numbers work, as in Java.)
enumerate: the index and the item together
The most common reason Java developers write a counting loop is “I need the item and its position”. In Python that’s enumerate:
for (int i = 0; i < chunks.size(); i++) {
String chunk = chunks.get(i);
System.out.println("Chunk " + i + ": " + chunk);
}for i, chunk in enumerate(chunks):
print(f"Chunk {i}: {chunk}")
for n, chunk in enumerate(chunks, start=1): # count from 1
print(f"{n}. {chunk}")enumerate hands you pairs, and i, chunk unpacks each pair into two names. Writing for i in range(len(chunks)): works too, but Python readers will see it as Java written in Python.
zip: two lists, side by side
When you walk two lists in step, Java makes you index both. Python zips them:
for (int i = 0; i < texts.size(); i++) {
store.add(texts.get(i), vectors.get(i));
}for text, vector in zip(texts, vectors):
store.add(text, vector)zip stops at the shorter list without an error. If the lists must match, say so: zip(texts, vectors, strict=True) raises an error when they don’t (Python 3.10+).
Looping over a dict
A dict is Python’s HashMap. Looping over it gives keys; .items() gives key and value together:
for (Map.Entry<String, Integer> e : counts.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}for word, count in counts.items():
print(f"{word} = {count}")Unlike Java’s HashMap, a Python dict keeps insertion order, so the loop runs in the order you added the keys.
while, break and continue
These work exactly as in Java:
attempts = 0
while attempts < 3:
attempts += 1
if call_api():
break
print("Retrying...")
There’s no do ... while. Write while True: with a break at the end instead. And Python has one oddity you may meet in other people’s code: a for or while can have an else block, which runs only if the loop finished without break. It’s handy for searches, but use it sparingly; many readers don’t know it.
The ternary, in plain words
Java’s cond ? a : b reads in Python like a sentence:
String label = text.length() > 1000 ? "long" : "short";label = "long" if len(text) > 1000 else "short"Value first, then the condition, then the fallback. Keep it to short expressions.
match: Python’s switch (and more)
Python 3.10 added match. For simple values it reads like a switch:
switch (event.type()) {
case "text" -> print(event.text());
case "tool_use" -> runTool(event);
default -> { }
}match event.type:
case "text":
print(event.text)
case "tool_use":
run_tool(event)
case _:
pass # _ is "default"; pass means "do nothing"There’s no fall-through and no break. Like Java 21’s pattern matching for switch, match can also take apart structures, such as case {"role": "user", "content": text}: on a dict. Many Python codebases still use plain if/elif chains, so expect both.
Traps for Java developers
- The missing colon.
if x > 0without:is the most common beginner error. Same forfor,while,defandclass. - The loop variable survives the loop. After
for doc in docs:,docstill holds the last item. Don’t rely on it. - Changing a list while looping over it. Removing items from
docsinsidefor doc in docs:skips elements, much like aConcurrentModificationExceptionwaiting to happen, except Python won’t warn you. Loop over a copy (for doc in docs[:]:) or build a new list. range(len(x))everywhere. It works, butenumerateandzipare clearer and harder to get wrong.
Key takeaways
elif, a colon, and indentation. No parentheses needed.- Every
forloop walks over items.rangegives numbers; the stop value is excluded. enumerategives index and item;zipwalks lists side by side;.items()walks a dict.while,breakandcontinuework as in Java; there’s nodo-while.- The ternary is
a if cond else b, andmatch/caseis Python’s switch.
Frequently asked questions
Does Python have a for loop like Java’s for (int i = 0; i < n; i++)?
No. Python’s for always loops over items. For counting, loop over range(n), which gives 0 to n - 1.
What does enumerate do in Python?
It wraps a list (or any iterable) and gives you pairs of index and item, so for i, item in enumerate(items): replaces a counting loop. Pass start=1 to count from 1.
What does zip do in Python?
It walks two or more lists at the same time and gives you one item from each per step. It stops at the shortest list, unless you pass strict=True.
Does Python have a switch statement?
Since Python 3.10, yes: match and case. It has no fall-through, uses case _: as the default, and can also match on the shape of lists, dicts and objects.
What is elif in Python?
elif is Python’s else if. You can chain as many as you need, followed by an optional else.
Next in the series: Python list and dict vs Java ArrayList and HashMap, with every collection method you use daily mapped to Python.
Comments