6. Loops

6.1. Loop though range

We start with a simple loop using for and range (see footnote 1). To loop though for all integer starting at 0 inclusive and ending at 5 exclusive:

[1]:
for i in range(5):
    print("value of i is now:", i)
value of i is now: 0
value of i is now: 1
value of i is now: 2
value of i is now: 3
value of i is now: 4

On the other hand, to loop though for all integer starting at 2 inclusive and ending at 5 exclusive:

[2]:
for i in range(2, 5):
    print("value of i is now:", i)
value of i is now: 2
value of i is now: 3
value of i is now: 4

6.2. Loop over other iterables

Python allows us to loop though any iterable object. We’ll see later the exact definition of an iterable object as well as how to create your custom ones. But for, here’s some of them with a learn by example method:

[3]:
sometuple = (4.3, 3.43, "name", 492)
somelist = [392, 3.43, 492]
someset = {4.3, 3.43, "name", 4.3, "name", 3.1}
for i in sometuple:
    print("sometuple element:", i)
for i in somelist:
    print("somelist element plus 100:", i + 100)
for i in someset:
    print("someset element:", i)
sometuple element: 4.3
sometuple element: 3.43
sometuple element: name
sometuple element: 492
somelist element plus 100: 492
somelist element plus 100: 103.43
somelist element plus 100: 592
someset element: 3.1
someset element: 3.43
someset element: 4.3
someset element: name

And here’s a more special one:

[4]:
somedict = {"ld": 4.3, "lp": 3.43}
for i in somedict:
    print("somedict element:", i)
somedict element: ld
somedict element: lp

And maybe, just maybe, not what you wanted. So here’s a possible solution:

[5]:
somedict = {"ld": 4.3, "lp": 3.43}
for k, v in somedict.items():
    print("somedict key", k, "has value", v)
somedict key ld has value 4.3
somedict key lp has value 3.43

And guess what, with enumerate you get a similar behavior for list and friends:

[6]:
sometuple = (4.3, 3.43, "name", 492)
somelist = [392, 3.43, 492]
someset = {4.3, 3.43, "name", 4.3, "name", 3.1}
for i, v in enumerate(sometuple):
    print("sometuple index", i, "has value", v)
for i, v in enumerate(somelist):
    print("somelist index", i, "has value + 100 equals to", v + 100)
for i, v in enumerate(someset):
    print("someset index", i, "has value", v)
sometuple index 0 has value 4.3
sometuple index 1 has value 3.43
sometuple index 2 has value name
sometuple index 3 has value 492
somelist index 0 has value + 100 equals to 492
somelist index 1 has value + 100 equals to 103.43
somelist index 2 has value + 100 equals to 592
someset index 0 has value 3.1
someset index 1 has value 3.43
someset index 2 has value 4.3
someset index 3 has value name

And of course, you can nest loops within loops:

[7]:
fruits = ["apple", "orange", "watermelon"]
modes = ["pure", "candied"]
for fruit in fruits:
    for mode in modes:
        print("I like", mode, fruit)
I like pure apple
I like candied apple
I like pure orange
I like candied orange
I like pure watermelon
I like candied watermelon

6.3. Break, continue

The Python keyword continue allows you to skip a single iteration of a loop. Suppose for instance that you don’t like orange, and want to skip it:

[8]:
fruits = ["apple", "orange", "watermelon"]
for fruit in fruits:
    if (fruit == "orange"):
        continue
    print("I like", fruit)
I like apple
I like watermelon

On the other hand, the Python keyword break allows you to get out of the loop all together. So if you hate pure orange so much, that after seeing it, you don’t want anything else anymore, then you can take advantage of break:

[9]:
fruits = ["apple", "orange", "watermelon"]
for fruit in fruits:
    if (fruit == "orange"):
        break
    print("I like", fruit)
I like apple

Note however that both continue and break only work on the most inner loop only, so,

[10]:
fruits = ["apple", "orange", "watermelon"]
modes = ["pure", "candied"]
for fruit in fruits:
    for mode in modes:
        if (fruit == "orange" and mode=="pure"):
            break
        print("I like", mode, fruit)
I like pure apple
I like candied apple
I like pure watermelon
I like candied watermelon

One solution to break from many loops is to nest everything within a function and return from such function:

[11]:
def somefunc():
    fruits = ["apple", "orange", "watermellon"]
    modes = ["pure", "candied"]
    for fruit in fruits:
        for mode in modes:
            if (fruit == "orange" and mode=="pure"):
                return
            print("I like", mode, fruit)
somefunc()
I like pure apple
I like candied apple

6.4. While loops

Despite not being as common as for loops in Python world, while are the tool of choice for many circumstances and are very simple to gasp, they’ll execute as long as the condition is True (or you use break):

[12]:
i = 0
number = 1.0
while number <= 1000:
    number *= 1.1 #inflation: 10% higher prices
    number /= 0.9 #promotion: 10% off today only
    i += 1
i
[12]:
35

Note that the condition is also evaluated on the first iteration of the loop, so if it’s False, the loop might not execute at all:

[13]:
someint = 100
while someint > 1000:
    print("I will never be shown T.T")

6.5. Footnotes

  1. Take a look at what list(range(6)) and list(range(3, 6)) does.