loading...

Charming the Python: Loops

vickilanger profile image Vicki (she/her) Updated on ・2 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Loops

Loops are meant to do repetitive things. Any time you see something that needs to be repeated, you should probably be using some sort of loop. For example, when washing dishes, you wet the dish, scrub it with soap, rinse the dish, dry the dish. Then you do this over and over until the dishes are done.

While loop

A while loop is used to execute a block of statements repeatedly while a given condition is satisfied

count = 0
while count < 5:
    print(count)  # prints the current count
    count = count + 1  # adds 1 to count each time
Enter fullscreen mode Exit fullscreen mode

For loop

For loops are meant to iterate over a sequence, such as a list, a tuple, a dictionary, a set, or a string.

pets = ['Puppy', "Cheeto", 'Remmy', 'Wiley', "Ruger", "Stick"]

for pet in pets:  # create new variable `pet`
    feed_pet  # feed each pet in list(pets)
    print(pet + " is fed")  # print a line about pet being fed
else:
    print('no more pets to feed')  # when no more pet in list(pets) print about that
Enter fullscreen mode Exit fullscreen mode

For those who like a bit of math:

numbers = (0,1,2,4,5)
for number in numbers:
    print(number)
0
1
2
4
5
Enter fullscreen mode Exit fullscreen mode

Break and Continue

break is used for getting out or stopping the loop

For example, the below while loop prints 0, 1, 2, but when it reaches 3 it stops

count = 0
while count < 5:
    print(count)  # prints the current count
    count = count + 1  # adds 1 to count each time
    if count == 3:
        break
Enter fullscreen mode Exit fullscreen mode

continue is used to stop the current iteration and move to the next one.

For example, the below while loop only prints 0, 1, 2,4 but skips 3.

count = 0
while count < 5:
    if count == 3:
        continue
    print(count)
    count = count + 1
Enter fullscreen mode Exit fullscreen mode

Example for loop continue

pets = ['Puppy', "Cheeto", 'Remmy', 'Wiley', "Ruger", "Stick"]

for pet in pets:
    if pet == 'Stick'
        continue  # skip feeding Stick and move on
    feed_pet
    print(pet + " is fed")
else:
    print('no more pets to feed')  # when no more pet in list(pets) print about that
Enter fullscreen mode Exit fullscreen mode

Pass

pass is basically used to say "hey, I'm still working on this and I just haven't filled in the codestuffs yet."
pass is used to bypass errors from incomplete code.

for pet in pets:
    pass
Enter fullscreen mode Exit fullscreen mode

Series based on

Discussion

pic
Editor guide