while
- conditional loopsfor
- counter controlled loopsTrue
or False
set of valuesTrue
False
while
Loop Statements (1)while
loops, are loops that will execute
zero or more times before it is terminatedwhile
loop structure:variable += 1
while
Loop Statements (2)x
is 0
and the loop
will increment x
for each iterationx < 10
0 1 2 3 4 5 6 7 8 9
while
Loop with a Break Statement (1)break
statements can be used to stop the
loop if a condition is evaluated to True
0 1 2 3 4 5
while
Loop with a Break Statement (2)True
value after the while
keywordx
until it
reaches a certain value
x
must be equal to
10
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
while
Loop with Continue Statementcontinue
statements can stop the current
iteration and continue onto the next1 2 3 4 6 7 8 9 10
while
Loop with an Else Statementelse
statements can be used to executee a
block of code when a condition has been met
True
0 1 2 3 4 5 6 7 8 9
x is no longer less than 10
for
Loop Statementsfor
loop is a loop that is designed to
increment a counter over a given range of valuesfor
loops are useful because…
False
condition to terminate the
loopfor
loop consists of the
following:
start < stop
start > stop
for
loops can also be iterated forwards by
using a positive step value1 2 3 4 5 6 7 8 9
for
loops can also be iterated backwards by
using a negative step value10 9 8 7 6 5 4 3 2
for i in range(1, 4, 1):
print(f"Iteration {i}: ")
for j in range(1, 4, 1):
print(i * j, end=" ")
print("\n\n\n")
Iteration 1: 1 2 3
Iteration 2: 2 4 6
Iteration 3: 3 6 9
for
loops are great for looping through
various objects:
4 0 6 1 C E M
module = [4061, "Programming and Algorithms", "Ian Cornelius"]
for item in module:
print("\n\n", item)
4061
Programming and Algorithms
Ian Cornelius
module = {"code": 4061,
"title": "Programming and Algorithms",
"leader": "Ian Cornelius"}
for key, value in module.items():
print("\n\n", key, "=", value)
code = 4061
title = Programming and Algorithms
leader = Ian Cornelius
module = {"code": 4061,
"title": "Programming and Algorithms",
"leader": "Ian Cornelius"}
for key in module.keys():
print("\n\n", key, "=", module[key])
code = 4061
title = Programming and Algorithms
leader = Ian Cornelius
module = {"code": 4061,
"title": "Programming and Algorithms",
"leader": "Ian Cornelius"}
for v in module.values():
print("\n\n", v)
4061
Programming and Algorithms
Ian Cornelius
module = {"code": 4061,
"title": "Programming and Algorithms",
"leader": "Ian Cornelius",
"team": ["Terry Richards", "Daniel Goldsmith"]}
for key in module.keys():
if type(module[key]) != list:
print("\n\n", key, ":", module[key])
else:
print("\n", key, ":", end=" ")
for i in range(len(module[key])):
print('\t', module[key][i], end=" ")
code : 4061
title : Programming and Algorithms
leader : Ian Cornelius
team : Terry Richards Daniel Goldsmith
boolean
expression to evaluate to False