Week 4: Loops in Python

CMPSC 100 Computational Expression

Janyl Jumadinova

Loops in Python

Repeating actions

What are Loops?

  • Loops allow us to repeat code multiple times
  • Instead of writing the same code over and over
  • Python has two main types of loops:
    • for loops - repeat a specific number of times
    • while loops - repeat while a condition is true

Why Use Loops?

Without a loop:

print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")

With a loop:

for i in range(5):
    print("Hello!")

The range() Function

  • range() creates a sequence of numbers
  • Very useful with for loops

Examples:

range(5)        # 0, 1, 2, 3, 4
range(1, 6)     # 1, 2, 3, 4, 5
range(2, 10, 2) # 2, 4, 6, 8

Basic For Loop

Structure:

for variable in range(number):
    # code to repeat

Example:

for count in range(3):
    print(f"Count is: {count}")

Output:

Count is: 0
Count is: 1
Count is: 2

For Loop with Custom Range

Example:

for day in range(1, 4):
    print(f"Day {day} of training")

Output:

Day 1 of training
Day 2 of training
Day 3 of training

Loops with Calculations

Example:

total = 0
for number in range(1, 6):
    total = total + number
    print(f"Adding {number}, total is now {total}")

print(f"Final total: {total}")

Output:

Adding 1, total is now 1
Adding 2, total is now 3
Adding 3, total is now 6
Adding 4, total is now 10
Adding 5, total is now 15
Final total: 15

For Loops with Strings

  • For loops can iterate through characters in a string
  • Each character becomes the loop variable

Example:

name = "CMPSC"
for letter in name:
    print(f"Letter: {letter}")

Output:

Letter: C
Letter: M
Letter: P
Letter: S
Letter: C

Accessing String Characters by Index

  • You can also use a for loop with indices to access characters
  • Use range() with the length of the string
  • Access each character using string[index]

Example:

word = "PYTHON"
for position in range(6):  # 6 characters in "PYTHON"
    print(f"Position {position}: {word[position]}")

Output:

Position 0: P
Position 1: Y
Position 2: T
Position 3: H
Position 4: O
Position 5: N

While Loops

  • While loops repeat code as long as a condition is True
  • Different from for loops - we don’t know exactly how many times it will run
  • Must be careful to avoid infinite loops

Structure:

while condition:
    # code to repeat
    # must change something to eventually make condition False

While Loop Example

Example:

count = 1
while count <= 3:
    print(f"Count is: {count}")
    count = count + 1  # Important: change the variable!

print("Loop finished!")

Output:

Count is: 1
Count is: 2
Count is: 3
Loop finished!

For Loop vs While Loop

For loop - when you know how many times:

for i in range(5):
    print("Hello!")

While loop - when you have a condition:

number = 1
while number <= 5:
    print("Hello!")
    number = number + 1

Both print “Hello!” 5 times, but use different approaches!

Nested Loops

  • A loop inside another loop
  • The inner loop runs completely for each iteration of the outer loop

Structure:

for outer_variable in range(number):
    for inner_variable in range(number):
        # code here runs multiple times

Simple Nested Loop Example

Example:

for row in range(1, 3):
    for col in range(1, 4):
        print(f"Position ({row}, {col})")

Output:

Position (1, 1)
Position (1, 2)
Position (1, 3)
Position (2, 1)
Position (2, 2)
Position (2, 3)

Nested Loops - Pattern Making

Example:

for row in range(1, 5):
    for star in range(row):
        print("*", end="")
    print()  # New line after each row

Output:

*
**
***
****

Key Points About Loops

  • Indentation matters - code inside the loop must be indented
  • Loop variable changes each time through the loop
  • Nested loops - inner loop completes fully for each outer loop iteration
  • range() - starts at 0 by default, stops before the end number
  • Be careful with while loops to avoid infinite loops