Tips/Tricks

Atom

Terminal

Reminders

Today

Repetition using for loops

To this point, all of our programs have been sequential - with one line of code following the other. Often, we need to repeat a task several times. If we know the number of times, we use definite loops which are called for loops in Python. The syntax is:

for VAR in SEQUENCE:
  BODY

For example, we can print numbers 1 through 5:

for i in [1,2,3,4,5]:
    print(i)

i is our loop variable - it keeps track of where we are in the sequence. Defining the sequence explicitly does not scale to large numbers (e.g., 1000) so we instead use the range(x) operator:

for i in range(5):
    print(i)

which outputs:

0
1
2
3
4

Exercise: What do these loops do?

What is the output of this loop?

for i in [0,1,2,3]:
  print(i*2)

Notice the special syntax that uses brackets around a sequence. This is how we designate a value of type list. A list is a collection of values itself, which can be of any type (e.g., int in the above example). Now try this example where the list consists of a sequence of strings:

print("Pets:")
for animal in ["Corgis", "Cavaliers", "Mini Ponies"]:
  print(animal)
print()
print("Done!")

Exercise: loop.py

cd
cd cs21/inclass/w02-nums-strs-loops
atom ./

Open loop.py to get some practice writing loops by completing one or more of the following tasks:

  1. Print the string tricky three times, once per line, using a loop.
  2. Print the squared value of the integers 1 through 5 (i.e., 1,4,9,16,25). Use the range function to define your sequence, and then manipulate i by adding 1 and squaring the value.
  3. Write a loop that repeats three times and asks the user for a number that you then square. Note that this loop shows that the loop variable isn't always used to do the calculation.
  4. Ask the user for an integer n and then print the values from n to 1 in reverse, with one number per line.