CMSC 201

Lab 5: Loops

For Loops

What are they?

A for loop is similar to a while loop.
For loops are normally used when you want to repeat a section of code n number of times.

How do I use them?

  • The syntax of a basic for loop is shown below:

  • for i in range(start, end, step):
        statements(s) 
    The above loop would start executing with i = start. After each iteration, i will be incremented by the step . The loop will end when i >= end.
    for i in range(0,10,3):
        print(i)
     
    Output:
    0
    3
    6
    9

    However, the only required argument is the end argument. The other two are optional.

    for i in range (3):
        print(i)
     
    Output:
    0
    1
    2
    for i in range (3, 8):
        print(i)
     
    Output:
    3
    4
    5
    6
    7

    The step can be negative to iterate backwards.

    for i in range (8, 3, -1):
        print(i)
     
    Output:
    8
    7
    6
    5
    4

    You can iterate through strings as well in Python.

    word = "hello"
    for w in word:
        print(w)
     
    Output:
    h
    e
    l
    l
    o