CSU East Bay logo

Chemistry 311

Loops in Python

Loops allow a program to repeat a block of code multiple times. In Python, loops are commonly used to process collections of data, perform repeated calculations, and automate tasks. Python provides two primary looping constructs: for loops and while loops.


for loops

A for loop is used to iterate over a sequence of values, such as a list, a string, or a range of numbers. The loop runs once for each item in the sequence.


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

In this example, the loop variable i takes on the values 0 through 4. The loop automatically stops when the sequence is exhausted.

for loops are ideal when:


while loops

A while loop repeats a block of code as long as a condition remains true. The condition is checked before each iteration.


    count = 0
    while count < 5:
        print(count)
        count += 1
      

In this example, the loop continues until count reaches 5. Unlike a for loop, the programmer is responsible for updating the condition inside the loop.

while loops are useful when:


Choosing between for and while

In many cases, either type of loop could be used, but choosing the right one improves clarity and reduces errors.

Big idea: for loops are best for structured, count-controlled repetition, while while loops are best for condition-controlled repetition.

Your turn

Problem 1
Which loop is most appropriate when you know in advance how many times the loop should run?
while loop
for loop
Either loop is required
Loops cannot be used for this task
Problem 2
What is the main risk when using a while loop?
Creating an infinite loop if the condition never becomes false
The loop can only run once
The loop cannot use variables
The loop must always use a list
Problem 3
What does the following code print?

for i in range(3):
    print(i)
          
1 2 3
1 2
0 1
0 1 2
Problem 4
Which situation is best suited for a while loop?
Looping over every element in a list
Repeating code exactly 10 times
Repeating until the user enters valid input
Printing the numbers from 1 to 5
Problem 5
Which statement best describes the difference between for and while loops?
for loops iterate over a sequence, while while loops repeat based on a condition
while loops are faster than for loops
for loops require integers, while while loops require booleans
for loops can only be used once

Key points (one glance)

Big picture: loops are a fundamental control structure in Python, enabling efficient repetition and automation by executing code blocks based on sequences or logical conditions.