This is an archived version of the course. Please see the latest version of the course.

Loops

while loops work pretty much the same as in Java, so we will not discuss it.

do-while loops do not exist in Python.

for loops in Python are different from the traditional for loops in Java, and are actually easier to understand. In fact, for loops in Python are more like for-each loops in Java (if you are familiar with it).

In Python, for loops iterate over an iterable, for example over a sequence like a list.

The code below is self explanatory and should even read like English.

words = ["I", "have", "a", "dream"]
for word in words:
    print(word)

This would be equivalent to the following in Java

// This is Java code, not Python!

String[] words = new String[] {"I", "have", "a", "dream"};

for (String word : words) {
    System.out.println(word);
}

for loops over Dictionaries

for iterates over the keys in dicts by default.

height_dict = {"Tom": 163, "Dick": 178, "Harry": 182}
for key in height_dict:
    print(f"{key}'s weight is {height_dict[key]}")

Use the items() method of dict to iterate over both keys and values simultaneously.

for (key, value) in height_dict.items():
    print(f"{key}'s weight is {value}")