CMPE 150

Introduction to Computing

Fall 2021

Created by Gökçe Uludoğan

### For Loops * Iterates over a collection of objects * Syntax: ```python for item in sequence: statements ``` * At each iteration * `item` takes the value of the next element in `sequence` * statements are executed for `item`

For Loops

Loop continues until the last item is reached.

Example: Iterating a sequence of numbers


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

Output

1
2
3
4

Execution

### The `range()` function * Generates numbers in given range. * `range(start, stop, step_size)` * **start:** lower limit. By default, 0. * **stop:** upper limit. Numbers are generated up to this number. * **step_size:** difference between each number. By default, 1. * start and step_size are the optional arguments.

Examples


for i in range(5):
    print(i, end=', ')

for i in range(5, 10):
    print(i, end=', ')

for i in range(2,8,2):
    print(i, end=', ')

Examples


for i in range(5):
    print(i, end=', ')

Output

0, 1, 2, 3, 4, 

for i in range(5, 10):
    print(i, end=', ')

for i in range(2,8,2):
    print(i, end=', ')

Examples


for i in range(5):
    print(i, end=', ')

Output

0, 1, 2, 3, 4, 

for i in range(5, 10):
    print(i, end=', ')

Output

5, 6, 7, 8, 9, 

for i in range(2,8,2):
    print(i, end=', ')

Examples


for i in range(5):
    print(i, end=', ')

Output

0, 1, 2, 3, 4, 

for i in range(5, 10):
    print(i, end=', ')

Output

5, 6, 7, 8, 9, 

for i in range(2,8,2):
    print(i, end=', ')

Output

2, 4, 6, 
### Nested Loop * A loop inside the body of the outer loop. * In each iteration of the outer loop, inner loop execute all its iteration. * Syntax ```python # outer for loop for element in sequence: # inner for loop for element in sequence: body of inner for loop body of outer for loop ```

Example: Multiplication Table

Execution

Example: Print Triangle

rows = 5
# outer loop
for i in range(1, rows + 1):
    # inner loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')

the outer loop: the number of rows print.

the inner loop: the total number of columns in each row.

Execution

References

  1. https://pythontutor.com/
  2. https://realpython.com/python-for-loop/
  3. https://www.programiz.com/python-programming/for-loop
  4. https://pynative.com/python-nested-loops/