## DEV Community is a community of 674,199 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Charming the Python: Loops

Vicki (she/her)
Vicki was once a manager of aircraft maintenance and is now charming Python. She coded #VetsWhoCode bot & Code Questions bot. When Vicki isn't petting her cat, she’s throwing a ball for her dogs.

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
``````

### 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
``````

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
``````

### 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
``````

`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
``````

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
``````

### 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
``````

Series based on