Joseph Haugh
University of New Mexico
while <<condition>>:
<<statements>>
while <<condition>>:
<<statements>>
n = 0
while n <= 3:
print("Hello!")
n += 1
How many times will Hello! be printed?
while <<condition>>:
<<statements>>
Let’s try another example:
sum_x = 0
n = 3
while n > 0:
x = int(input())
sum_x += x
n -= 1
print(sum_x)
What is this code doing?
while <<condition>>:
<<statements>>
The stop condition can also depend on input to the program:
x = int(input())
while x != 7:
x = int(input())
print(x)
while loops Python also gives us for loopsfor <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
for <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
for <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
Remember our print Hello! example? Lets write it with while and for:
for <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
What does the following code do?
sum_x = 0
for x in range(7, 11):
print(x)
sum_x += x
print(sum_x)
for <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
You can also make the range function change the variable by a different amount each iteration:
for x in range(2, 10, 2):
print(x)
Will 10 be printed?
for <<variableName>> in range(<<startValue>>, <<endValue>>):
<<statements>>
You can also count down:
for x in range(10, 2, -2):
print(x)
Will 2 be printed?