Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Links | Search | Bio |

Guide to Python (University at Buffalo Version)


Chapter 4: Using Python Loops

Python provides a few different control structures that allow you to loop through data using a set of statements.

The Python for Loop

The for statement provides a way to loop through a statement, or group of statements, a number of times.

# print only even numbers 
for i in range(10):
  if (i%2):
    print(i)
Figure 4-1: A Python for Loop
1
3
5
7
9
Figure 4-2: Python for Loop Output

Python for Loop for Arrays

Python does not have a foreach loop statement. You can use the for statement to "walk" through an associative array.

teamArray = {"name": "Yankees", "city": "New York"}
for key, value in teamArray.items():
  print(f"{key}: {value}")
Figure 4-3: Python for (array) Loop
name: Yankees
city: New York
Figure 4-4: Python for (array) Loop Output

The Python while Loop

The while loop statement provides a way to to perform a statement or statements based on a condition being true or false.

# Example of a while loop in Python
# Initialize a variable
count = 1
while
  count <= 5:
  print(f"Count is: {count}")
  count += 1
Figure 4-5: Python while Loop
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Figure 4-6: Python while Loop Output

The Python do / while Loop

Python does not have a do/while set of statements. do ... while loop statements provide a way to to perform a statement or statements based on a condition being true or false. A do ... while loop tests the condition at the end of the loop. So, a do ... while loop will always execute at least once.

# Example of a simulated do-while loop in Python using a while loop
# Initialize a variable
count = 0
while True:
  # Code block to execute 
  print(f"Count is: {count}") 
  count += 1  
  # Condition to break the loop  
  if count >= 5:  
    break
  
Figure 4-7: Python Simulated do / while Loop
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Figure 4-8: Python Simulated do / while Loop Output

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2025 Jim Gerland