Skip to content

Branching and Loops

if Statements

Python if Statement

python
# Python - Basic if statement
age = 18

if age >= 18:
    print("Adult")
elif age >= 12:
    print("Teenager")
else:
    print("Child")

# Conditional expression (ternary operator)
status = "Adult" if age >= 18 else "Minor"
print(status)

# Multiple conditions
score = 85
if 90 <= score <= 100:
    grade = "A"
elif 80 <= score < 90:
    grade = "B"
elif 70 <= score < 80:
    grade = "C"
else:
    grade = "D"

JavaScript if Statement

javascript
// JavaScript - Basic if statement
const age = 18;

if (age >= 18) {
  console.log("Adult");
} else if (age >= 12) {
  console.log("Teenager");
} else {
  console.log("Child");
}

// Conditional expression (ternary operator)
const status = age >= 18 ? "Adult" : "Minor";
console.log(status);

// Multiple conditions
const score = 85;
let grade;
if (score >= 90 && score <= 100) {
  grade = "A";
} else if (score >= 80 && score < 90) {
  grade = "B";
} else if (score >= 70 && score < 80) {
  grade = "C";
} else {
  grade = "D";
}

Condition Comparison

| Operation | Python | JavaScript | | ----------- | ---------------- | ---------- | --- | --- | | Equality | == or is | === | | Inequality | != or is not | !== | | Logical AND | and | && | | Logical OR | or | | | | | Logical NOT | not | ! |

for and while Statements

Python Loops

python
# Python - for loop
fruits = ["apple", "banana", "orange"]

# Iterate over a list
for fruit in fruits:
    print(fruit)

# Iterate over a range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# Iterate over a dictionary
person = {"name": "Alice", "age": 25}
for key, value in person.items():
    print(f"{key}: {value}")

# Iterate with an index
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Python - while loop
count = 0
while count < 5:
    print(count)
    count += 1

# break and continue
for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 7:
        break     # Stop at 7
    print(i)

JavaScript Loops

javascript
// JavaScript - for loop
const fruits = ["apple", "banana", "orange"];

// Iterate over an array
for (const fruit of fruits) {
  console.log(fruit);
}

// Traditional for loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

// Iterate over an object
const person = { name: "Alice", age: 25 };
for (const [key, value] of Object.entries(person)) {
  console.log(`${key}: ${value}`);
}

// Iterate with an index
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

// JavaScript - while loop
let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

// break and continue
for (let i = 0; i < 10; i++) {
  if (i === 3) {
    continue; // Skip 3
  }
  if (i === 7) {
    break; // Stop at 7
  }
  console.log(i);
}

Loop Method Comparison

FeaturePythonJavaScript
Iterate list/arrayfor item in listfor (const item of array)
Iterate with indexenumerate()forEach() or for (let i = 0; ...)
Iterate dictionary/objectitems()Object.entries()
Range looprange(n)for (let i = 0; i < n; i++)

List and Dictionary Comprehensions

Python List Comprehensions

python
# Python - List comprehensions
numbers = [1, 2, 3, 4, 5]

# Basic list comprehension
squares = [x**2 for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# List comprehension with condition
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(even_squares)  # [4, 16]

# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Dictionary comprehension
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)  # {'Alice': 5, 'Bob': 3, 'Charlie': 7}

# Set comprehension
numbers = [1, 2, 2, 3, 3, 4, 5]
unique_squares = {x**2 for x in numbers}
print(unique_squares)  # {1, 4, 9, 16, 25}

JavaScript Array Methods

javascript
// JavaScript - Array methods
const numbers = [1, 2, 3, 4, 5];

// map method (similar to list comprehension)
const squares = numbers.map((x) => x ** 2);
console.log(squares); // [1, 4, 9, 16, 25]

// filter + map (list comprehension with condition)
const evenSquares = numbers.filter((x) => x % 2 === 0).map((x) => x ** 2);
console.log(evenSquares); // [4, 16]

// flatMap (nested list comprehension)
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const flattened = matrix.flatMap((row) => row);
console.log(flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Object comprehension (using reduce)
const names = ["Alice", "Bob", "Charlie"];
const nameLengths = names.reduce((acc, name) => {
  acc[name] = name.length;
  return acc;
}, {});
console.log(nameLengths); // {Alice: 5, Bob: 3, Charlie: 7}

// Set comprehension
const uniqueSquares = new Set(numbers.map((x) => x ** 2));
console.log([...uniqueSquares]); // [1, 4, 9, 16, 25]

Comprehensions vs. Array Methods Comparison

FeaturePython ComprehensionJavaScript Array Method
Transformation[f(x) for x in list]list.map(f)
Filtering[x for x in list if condition]list.filter(condition)
Filtering+Transform[f(x) for x in list if condition]list.filter(condition).map(f)
Nesting[item for row in matrix for item in row]matrix.flatMap(row => row)

Advanced Looping Techniques

Python Advanced Techniques

# Python - else in loops
for i in range(5):
    if i == 6:  # This condition is never met
        break
else:
    print("Loop finished without break")  # This will be printed

# Using zip to iterate over multiple lists
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

JavaScript Advanced Techniques

javascript
// JavaScript - Simulating else in loops
let broke = false;
for (let i = 0; i < 5; i++) {
  if (i === 6) {
    broke = true;
    break;
  }
}
if (!broke) {
  console.log("Loop finished without break");
}

// No direct equivalent for zip, but can be done with indexing
const names = ["Alice", "Bob"];
const ages = [25, 30];
names.forEach((name, index) => {
  const age = ages[index];
  console.log(`${name} is ${age} years old`);
});

Exercises

  1. Write a program that outputs a grade based on a score (A, B, C, D)

Reference Answer:

python
# Python
score = 85
if 90 <= score <= 100:
    grade = "A"
elif 80 <= score < 90:
    grade = "B"
elif 70 <= score < 80:
    grade = "C"
else:
    grade = "D"
print(grade)
javascript
// JavaScript
let score = 85;
let grade;
if (score >= 90 && score <= 100) {
  grade = "A";
} else if (score >= 80 && score < 90) {
  grade = "B";
} else if (score >= 70 && score < 80) {
  grade = "C";
} else {
  grade = "D";
}
console.log(grade);
  1. Use a loop to calculate the sum of numbers from 1 to 100

Reference Answer:

python
# Python
s = 0
for i in range(1, 101):
    s += i
print(s)
javascript
// JavaScript
let s = 0;
for (let i = 1; i <= 100; i++) {
  s += i;
}
console.log(s);
  1. Create a list comprehension to generate the squares of even numbers from 1 to 20

Reference Answer:

python
# Python
even_squares = [x**2 for x in range(1, 21) if x % 2 == 0]
print(even_squares)
javascript
// JavaScript
let evenSquares = [];
for (let x = 1; x <= 20; x++) {
  if (x % 2 === 0) evenSquares.push(x ** 2);
}
console.log(evenSquares);
// Alternatively:
let evenSquares2 = Array.from({ length: 20 }, (_, i) => i + 1)
  .filter((x) => x % 2 === 0)
  .map((x) => x ** 2);
console.log(evenSquares2);
  1. Compare the loop syntax differences between Python and JavaScript

Reference Answer:

  • Python: for item in list, while condition, enumerate, range, for key, value in dict.items()
  • JavaScript: for (let i = 0; i < n; i++), for...of, for...in, arr.forEach, Object.entries(obj)
  1. Implement a simple guess number game

Reference Answer:

python
# Python
import random
answer = random.randint(1, 10)
while True:
    guess = int(input("Guess a number between 1 and 10: "))
    if guess == answer:
        print("Correct!")
        break
    elif guess < answer:
        print("Too low")
    else:
        print("Too high")
javascript
// JavaScript (Node.js)
const readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});
const answer = Math.floor(Math.random() * 10) + 1;
function ask() {
  readline.question("Guess a number between 1 and 10: ", (input) => {
    const guess = parseInt(input);
    if (guess === answer) {
      console.log("Correct!");
      readline.close();
    } else if (guess < answer) {
      console.log("Too low");
      ask();
    } else {
      console.log("Too high");
      ask();
    }
  });
}
ask();

Next Steps

Now you have mastered Python's control flow statements, we will move on to learning functional programming.