Basic Python Loops Tutorial

in #python7 years ago

Original image no longer available

Lets get loopy!

For loops



Some simple looping techniques without going too much into everything. First we need something to play with. How about a list of things?

things = ['SpongeBob SquarePants', 'Patrick Star', 'Gary the Snail', 1, 2, 3]



Now start the looping...

for thing in things:
    print(thing)



Which will print each item in the list on a new line. If, for some reason, you'd like to loop over the individual letters in these strings you can.

for thing in things:
    for thingy in thing:
        print(thingy)



Which spews out this (a bit pointless for now but you get the idea).

S
p
o
n
g
e
B
o
b

S
q
u
...



Notice that there are 3 integers at the end of the list. Hunt them down.

integers = []

for thing in things:
    if isinstance(thing, int):
        integers.append(thing)

print(integers)



We can use range() to choose how many times to iterate over the loop. Let's use this and our new list to create another pointless list of integers rounded to 1 decimal place.

pointless = []
counter = 0

for integer in integers:
    for x in range(integer):
        silly = round(counter + (x * 3.14), 1)
        pointless.append(silly)
        counter += 1

print(pointless)



To be honest.... If we wanted a list of random integers it'll be much easier just to generate some and use range again to choose how many.

from random import randint

data = []

for i in range(8):
    x = randint(0, 9999999)
    data.append(x)

print(data)



Which gives us this glorious list of beautiful integers.

[2204750, 5804939, 7561118, 5774771, 8124467, 332380, 2428940, 3355867]


While loops



We also have while loops. We can use conditions with these.

from time import sleep

counter = 0

while counter < 10:
    counter += 1
    print(counter)
    sleep(0.2)



An endless loop goes a little something like this (press Ctrl + C to stop it).

from time import sleep

counter = 0

while True:
    counter += 1
    print(counter)
    sleep(0.2)


Looping over dictionaries



First we'll build a dictionary. We'll throw in the glorious list we generated earlier also.

data = {
    'name': 'Bob',
    'age': 20,
    'hobby': 'laughing',
    'integers': [2204750, 5804939, 7561118, 5774771, 8124467, 332380, 2428940, 3355867]
}



And now we'll loop over it and as we know 'integers' is a list we can loop over that when it gets to it.

for key, value in data.items():
    if key == 'integers':
        print(key)
        for x in value:
            print(x)
    else:
        print(key, value)



We can target individual values very easily.

print(data['name'])

for x in data['integers']:
    print(x)



And just for fun we'll find the difference between the integers as we loop through them.

d = []
gap = 0

for x in data['integers']:
    d.append(x - gap)
    gap = x

print(d)



Thanks for reading. x

Resources