Python vs. JavaScript: A Guide to Control Flow (Branching & Looping)
This document aims to detail the syntactical and philosophical differences in branching (conditional statements) and looping (iteration) between Python and JavaScript for developers familiar with one of the languages.
References:
- Comparing JavaScript and Python: Loops and If-Else Statements
- Python vs. JavaScript for Web Development: An In-depth Analysis
Core Syntax Differences at a Glance
Feature | Python | JavaScript |
---|---|---|
Conditional Parentheses | Not required () | Required () |
Code Blocks | Colon : with mandatory indentation | Curly braces {} |
Multi-way Branching Keyword | elif | else if |
Collection Looping | for item in iterable: | for (let item of iterable) (for values) |
Object Property Looping | for key in dict: | for (let key in object) (for keys/properties) |
Loop else Clause | Supported (for /while...else ) | Not supported |
Ternary Operator | val_true if condition else val_false | condition ? val_true : val_false |
1. Conditional Statements
Conditional statements allow a program to execute different code paths based on different conditions.
if...else
Structure
This is the most basic conditional statement.
Python:
x = 10
if x > 5:
print("x is greater than 5") # Relies on colon and indentation
else:
print("x is not greater than 5")
JavaScript:
let x = 10;
if (x > 5) {
console.log("x is greater than 5"); // Relies on parentheses and curly braces
} else {
console.log("x is not greater than 5");
}
if...elif...else
Multi-way Branching
Used when there are multiple mutually exclusive conditions to check.
Python: Uses the elif
keyword, maintaining vertical alignment of the code.
grade = 85
if grade >= 90:
print("A")
elif grade >= 80: # Note: elif
print("B")
elif grade >= 70:
print("C")
else:
print("D")
JavaScript: Uses the else if
keyword, which can lead to nested code blocks.
let grade = 85;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) { // Note: else if
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else {
console.log("D");
}
Ternary Operator
Used for simple conditional assignments in a single line.
Python: The syntax is closer to natural language, with the condition in the middle.
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # -> "adult"
JavaScript: Uses the C-style ? :
syntax.
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // -> "adult"
2. Looping Statements
Loops are used to execute a block of code repeatedly.
while
Loop
Repeats a block of code as long as a condition is true. The syntax differences are similar to the if
statement.
Python:
count = 0
while count < 3:
print(count)
count += 1
JavaScript:
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
for
Loop - Iterating Over Collections
This is one of the most significant areas of difference between the two languages.
Python: Python uses a unified for...in...
syntax to iterate over any iterable object (list, tuple, dictionary, set, string, etc.).
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over a dictionary (iterates over keys by default)
my_dict = {"a": 1, "b": 2}
for key in my_dict:
print(f"Key: {key}, Value: {my_dict[key]}")
# More elegantly iterate over dictionary key-value pairs
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
JavaScript: JavaScript provides two different kinds of for
loops for different scenarios.
for...of
(Recommended for iterating over values): This is the most direct equivalent to Python'sfor...in
. It is used to iterate over the values of an iterable object (like an array, string, or Set).javascript// Iterate over an array const fruits = ["apple", "banana", "cherry"]; for (const fruit of fruits) { console.log(fruit); }
for...in
(For iterating over object properties): This loop is used to iterate over the keys (property names) of an object. It is not recommended for iterating over arrays because it will also iterate over properties on the prototype chain and does not guarantee order.javascript// Iterate over an object const myObject = { a: 1, b: 2 }; for (const key in myObject) { console.log(`Key: ${key}, Value: ${myObject[key]}`); }
for
Loop - Iterating by Range/Index
Python: Python does not have a C-style for
loop. Instead, it uses the range()
function to generate a sequence of numbers, which is then iterated over with for...in
.
# Loop 5 times (from 0 to 4)
for i in range(5):
print(i)
# From 2 to 5 (not including 6)
for i in range(2, 6):
print(i)
JavaScript: Uses the classic C-style for
loop syntax.
// Loop 5 times (from 0 to 4)
for (let i = 0; i < 5; i++) {
console.log(i);
}
// From 2 to 5
for (let i = 2; i <= 5; i++) {
console.log(i);
}
3. Loop Control and Special Syntax
break
and continue
The functionality and usage of these two keywords are exactly the same in Python and JavaScript.
break
: Immediately terminates and exits the entire loop.continue
: Immediately ends the current iteration and proceeds to the next one.
# Python example
for i in range(5):
if i == 3:
break # Exits the loop when i is 3
print(i) # Outputs 0, 1, 2
// JavaScript example
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skips the current iteration when i is 2
}
console.log(i); // Outputs 0, 1, 3, 4
}
Loop else
Clause (Python-specific)
This is a unique and powerful Python feature with no equivalent in JavaScript. A for
or while
loop can have an else
clause that is executed only when the loop completes normally (i.e., was not interrupted by a break
statement).
This is particularly useful for implementing "search" logic: if you find what you're looking for, you break
; if the loop finishes without finding it, the else
block is executed.
# Example: Find a number in a list
my_list = [1, 2, 3, 4, 5]
num_to_find = 6
for num in my_list:
if num == num_to_find:
print(f"Found the number: {num_to_find}")
break
else:
# This will only execute if the for loop was not broken
print(f"Did not find the number in the list: {num_to_find}")
# Output: "Did not find the number in the list: 6"
Core Comparison
- Syntactic Simplicity: Python's mandatory indentation and lack of parentheses make the code visually cleaner with less symbolic noise.
- Design Philosophy: Python leans towards providing a single, general-purpose tool (like
for...in
for all iteration), whereas JavaScript provides more specialized tools for different scenarios (for...of
vs.for...in
vs. C-stylefor
). - Unique Features: Python's loop
else
clause provides elegant syntactic sugar for specific algorithmic patterns, reflecting its "batteries included" design philosophy.
4. Python's Indentation Rule: The Cornerstone of Code Blocks
Unlike JavaScript, which uses curly braces {}
to define code blocks, Python uses indentation for the same purpose. This is one of Python's most iconic features and one that beginners need to adapt to the most.
Core Rules
- Start of a Block: A new code block typically begins after a statement ending in a colon (
:
), such asif
,elif
,else
,for
,while
,def
,class
. - Consistent Indentation Level: All statement lines within the same code block must have the same amount of leading whitespace (the same indentation level).
- Indentation Medium: You can use spaces or tabs for indentation, but you absolutely cannot mix them. It is crucial to stick to one style within a project.
- PEP 8 Guideline: Python's official style guide (PEP 8) strongly recommends using 4 spaces for each level of indentation. The vast majority of Python developers and tools follow this standard.
- End of a Block: When a line of code's indentation returns to the previous level, it signifies the end of the current code block.
Example Breakdown
The following code demonstrates indentation rules in a nested structure:
for i in range(5):
print(f"Outer loop, i = {i}") # First level of indentation (4 spaces)
if i % 2 == 0:
print(f" i ({i}) is an even number") # Second level (8 spaces)
if i == 0:
print(" i is 0") # Third level (12 spaces)
print(" Even number check finished") # Back to the second level
print(f"Processing for i={i} finished") # Back to the first level
print("Loop finished") # Top-level code, no indentation
Fundamental Difference from JavaScript
- Python: Whitespace is syntactically significant. Incorrect indentation will cause an
IndentationError
, and the program will not run. - JavaScript: Whitespace is not syntactically significant and is only used to improve readability. Code blocks are defined exclusively by
{}
, and the indentation style does not affect the program's execution.