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 C++, 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 C++, and are actually easier to understand. In fact, for loops in Python are for-each loops in C++ (if you have come across this).

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)

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}")