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)
for
Loop1 3 5 7 9
for
Loop OutputPython 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}")
for
(array) Loopname: Yankees city: New York
for
(array) Loop OutputThe 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
while
LoopCount is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
while
Loop OutputThe 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
do / while
LoopCount is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4
do / while
Loop Output