Repeat... and Repeat!

There is one thing computers do far better than people: repeating the same task thousands of times without getting tired.

This time, we will learn how to make Python repeat things using loops.


Repeat 10 times (for loop)

The most common loop is for. For example, how would you print “Hello, Python!” 10 times?

Type this in PyCharm.

for i in range(10):
    print("Hello, Python!")

In plain English:

Repeat within the range of 10:
    print "Hello, Python!"

When you run it, it prints 10 greetings in the blink of an eye.


Repeat while counting

In the code above, what is i? It is the number that tells you which repetition you are on. (Remember: computers count from 0!)

for i in range(5):
    print(i, "time(s) so far.")

Translation:

Repeat while putting numbers 0 to 4 (total 5 times) into i:
    print i and "time(s) so far."

Result:

0 time(s) so far.
1 time(s) so far.
2 time(s) so far.
3 time(s) so far.
4 time(s) so far.

Take items out of a bundle one by one

Remember the list ([]) we learned about in variables? We can loop through a list and take each item out.

foods = ["chicken", "pizza", "tteokbokki"]

for food in foods:
    print(food, "sounds delicious!")

Translation:

Repeat by taking each food from the foods bundle and naming it food:
    print food and "sounds delicious!"

Repeat until a condition fails (while loop)

while means “while something is true.” It tells the computer to keep looping while the answer is yes.

energy = 3

while energy > 0:
    print("Still going! Energy left:", energy)
    energy = energy - 1

print("I am exhausted...")

Translation:

Remember that energy is 3

While energy is greater than 0:
    print current energy
    subtract 1 from energy and remember it again (use one energy)

(After the loop) print "I am exhausted..."

Warning: infinite loops

What happens if you forget energy = energy - 1 in the while loop? The computer will repeat forever because the energy never goes down.

This is called an infinite loop. In PyCharm, click the red stop button (square icon) to stop it.

Now you have a powerful tool to make the computer do repetitive work for you.