The first line after the loop.

Loops (While and For)
CSE 1310 – Introduction to Computers and Programming
1
Motivation
• Suppose we want to write a program that
does this:
– Ask the user to input an integer N.
– Prints out all integers between 0 and N.
• The elements of Python that we have covered
so far are not sufficient for writing this
program.
• What is missing: the ability to repeat some
instructions as many times as we want.
while loops
• A while loop is defined as follows:
while boolean_expression:
line 1
line 2
…
line n
• Line 1, line 2, …, line n are called the body of the
while loop.
3
while loop execution
while boolean_expression:
line 1
line 2
…
line n
first line after loop
• This is how a while loop gets executed:
– Step 1: evaluate boolean_expression.
– Step 2: If the expression is false, go to the first line after
the loop.
– Step 3: If expression is true, execute the body of the while
loop, and go back to step 1.
4
An example of a while loop
number_text = input("enter an integer: ")
number = int(number_text)
i = 0
while (i <= number):
print(i)
i = i+1
print("done with the while loop")
5
while loops: indentation matters
number_text = input("enter an integer: ")
number = int(number_text)
i = 0
while (i <= number):
print(i)
i = i+1
print("done with the while loop")
What does this program do?
6
Designing a while loop
• When you design a while loop, you need to
make sure that the loop will terminate exactly
when needed, not before, and not after.
• You will need to define a test (boolean
expression), that determines when to stay in
the loop and when to exit.
• You need to update variables within the body
of the loop, as needed.
7
for loops (simplest version)
• A for loop can be defined as follows (note: this
definition will be extended when we talk about lists).
for variable in range(from, to):
line 1
line 2
…
line n
• Line 1, line 2, …, line n are called the body of the
for loop.
8
for loop execution (simplest version)
for variable in range(from, to):
line 1
line 2
…
line n
first line after loop
• This is how a for loop gets executed:
–
–
–
–
Step 1: variable = from
Step 2: If variable >= to, go to first line after the loop.
Step 3: execute the body of the loop (lines 1 to n).
Step 4: update variable to variable + step, and go to step 2 9
An example of a for loop
number_text = input("enter an integer: ")
number = int(number_text)
for i in range(0, number+1):
print(i)
print("done with the for loop")
10
WARNING about using range
• If you want to process the integers between X
and Y (including X and Y), you need to use
range(X, Y+1).
• If you use range(X, Y), the for loop will go up
to Y-1, not up to Y.
• This is an extremely common source of bugs.
11
for loops, version 2
• A for loop can also be defined as follows (note:
this definition will be extended when we talk about
lists).
for variable in range(from, to, step):
line 1
line 2
…
line n
• Line 1, line 2, …, line n are called the body of the
for loop.
12
for loop execution
for variable in range(from, to, step):
line 1
line 2
…
line n
first line after loop
• This is how a for loop gets executed:
– Step 1: variable = from
– Step 2: If step is positive and variable >= to, or step is
negative and variable <= to, go to first line after the loop.
– Step 3: variable = variable + step
– Step 4: execute the body of the loop (lines 1 to n).
– Step 5: go to step 2
13
A for loop with a step
number_text = input("enter an integer: ")
number = int(number_text)
for i in range(0, number+1, 13):
print(i)
print()
print("printed all numbers between 0 and", number)
print("that are divisible by 13")
14
A for loop with a negative step
number_text = input("enter an integer: ")
number = int(number_text)
for i in range(number, -1, -1):
print(i)
print()
print("printed all numbers between", number)
print("and 0 in reverse order")
15
A for loop with a negative step
number_text = input("enter an integer: ")
number = int(number_text)
for i in range(number, -1, -1):
print(i)
print()
print("printed all numbers between", number)
print("and 0 in reverse order")
Note that the second argument of the range is -1, not 0.
16
The break statement
• The break statement forces termination of the current
while loop or for loop.
• Example: print the first number >= N that is divisible by 13.
N = int(input("enter an integer: "))
i = N
while True:
if (i % 13 == 0):
print("first number >=", N, "divisible by 13 is ", i)
break
i = i+1
17
The continue statement
• The continue statement skips the rest of the body of the
loop and goes directly to the next iteration (or to
termination).
• Example: print numbers between 1 and N that are divisible by
13.
N = int(input("enter an integer: "))
for i in range(0, N+1):
if (i % 13 != 0):
continue
print(i)
18
for loops, general version
• A for loop, in general, is defined as follows.
for variable in sequence_of_values:
line 1
line 2
…
line n
• Line 1, line 2, …, line n are called the body of the for
loop.
• sequence_of_values can be, among other things,
a string or a list. We will cover lists later in the course.
19
for loop execution
for variable in sequence_of_values:
line 1
line 2
…
line n
first line after loop
• This is how a for loop gets executed:
– Step 1: variable = first value from sequence_of_values (if
sequence_of_values is empty, go to first line after the loop.)
– Step 2: execute the body of the loop (lines 1 to n).
– Step 3: if variable has received the last value in sequence_of_values, exit
the loop (go to the first line after the loop).
– Step 4: set variable equal to next value in sequence_of_values, and go to
20
Step 2.
Sequences of Values
• range(X, Y):
– X and Y must be integers.
– range(X, Y) generates the sequence X, X+1, ..., Y-2, Y-1.
– Notice that this sequence EXCLUDES Y.
• range(X, Y, step)
– X, Y, step must all be integers.
– range(X, Y, step) generates the sequence:
X, X+1*step, X+2*step, …, X+k*step
where k is the largest integer such that:
• X+k*step < Y (if step is positive)
• X+k*step > Y (if step is negative)
21
Sequences of Values
• Any string is a sequence.
– String 'hello' is the sequence of values:
'h', 'e', 'l', 'l', o.
22
Example 1: for loop with a string
text = 'hello'
for i in text:
print(i)
• What values will variable i take in the for loop?
• What will the for loop print?
23
Example 1: for loop with a string
text = 'hello'
for i in text:
print(i)
• What values will variable i take in the for loop?
• First 'h', then 'e', then 'l', then 'l', then o.
• What will the for loop print?
h
e
l
l
o
24
Example 2: for loop with a string
text = input("enter some text: ")
counter = 0
for i in text:
print(i)
if (i == 'a'):
print("found an 'a'")
counter = counter+1
print("\nThe letter 'a' appears", counter, "times")
25
Example 2: for loop with a string
text = input("enter some text: ")
counter = 0
for i in text:
print(i)
if (i == 'a'):
print("found an 'a'")
counter = counter+1
print("\nThe letter 'a' appears", counter, "times")
New elements: string equality, single quote within double quotes, "\n"
26
Example 3: for loop with a string
# count the number of vowels in text entered by the user.
text = input("enter some text: ")
vowel_counter = 0
for i in text:
if (i in 'aeiouyAEIOUY'):
vowel_counter = vowel_counter + 1
print("\nThe text contains", vowel_counter, "vowels.")
27
break
while boolean_expression:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a break within the body of
the while loop.
• What line of code will be executed next?
28
break
while boolean_expression:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a break within the body of
the while loop.
• What line of code will be executed next?
– The first line after the loop.
29
break
for variable in sequence_of_values:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a break within the body of
the for loop.
• What line of code will be executed next?
30
break
for variable in sequence_of_values:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a break within the body of
the for loop.
• What line of code will be executed next?
– The first line after the loop.
31
continue
while boolean_expression:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a continue within the body
of the while loop.
• What line of code will be executed next?
32
continue
while boolean_expression:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a continue within the body
of the while loop.
• What line of code will be executed next?
– while boolean_expression.
33
continue
for variable in sequence_of_values:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a continue within the body
of the for loop.
• What line of code will be executed next?
34
continue
for variable in sequence_of_values:
line 1
line 2
…
line n
first line after loop
• Suppose that we execute a continue within the body
of the for loop.
• What line of code will be executed next?
– if we did not reach the last value in sequence_of_values,
variable gets updated to next value, and we move to line 1.
– else, we go to the first line after the loop.
35
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
break
...
first line after loop2
...
first line after loop1
• Suppose some break line belongs to multiple loops.
• If that break statement is executed, what line of code do we go to?
36
Nested Loops
• A loop can be part of another group.
• A loop that is a part of another group is called a nested
loop.
• Example 1:
for a in range(1, 11):
# start of loop 1
print("multiples of ", a, ":")
for b in range(1, 11):
# start of loop 2
print(a, "*", b, "=", a*b)
print()
37
Nested Loops
• A loop can be part of another group.
• A loop that is a part of another group is called a nested
loop.
• Example 2:
a = 1
while a <= 10:
# start of loop 1
print("multiples of ", a, ":")
for b in range(1, 11):
# start of loop 2
print(a, "*", b, "=", a*b)
print()
a = a + 1
38
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
break
...
first line after loop 2
...
first line after loop 1
• Suppose some break line belongs to multiple loops.
• If that break line is executed, what line of code do we go to?
39
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
break
...
first line after loop 2
...
first line after loop 1
• Suppose some break line belongs to multiple loops.
• If that break line is executed, what line of code do we go to?
– The first line after the innermost loop containing the break40 .
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
break
...
first line after loop 2
...
first line after loop 1
• What line is executed after the break in this example?
41
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
break
...
first line after loop 2
...
first line after loop 1
• What line is executed after the break in this example?
– The innermost loop that the break belongs to is loop 2.
– The next line will be the first line after loop 2 (shown in green).
42
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
first line after loop 2
...
break
...
first line after loop 1
• What line is executed after the break in this example?
43
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
first line after loop 2
...
break
...
first line after loop 1
• What line is executed after the break in this example?
– The innermost loop that the break belongs to is loop 1.
– The next line will be the first line after loop 1 (shown in green).
44
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
continue
...
first line after loop 2
...
first line after loop 1
• Suppose some continue line belongs to multiple loops.
• If that continue line is executed, what line of code do we go to?
45
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
continue
...
first line after loop 2
...
first line after loop 1
• Suppose some continue line belongs to multiple loops.
• If that continue line is executed, what line of code do we go to?
– The first line of the innermost loop containing the continue.
46
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
continue
...
first line after loop 2
...
first line after loop 1
• What line is executed after continue in this example?
47
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
continue
...
first line after loop 2
...
first line after loop 1
• What line is executed after continue in this example?
– The innermost loop that the continue belongs to is loop 2.
– The next line will be the first line of loop 2 (shown in green).48
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
first line after loop 2
...
continue
...
first line after loop 1
• What line is executed after continue in this example?
49
Break and Continue in Nested Loops
for variable1 in sequence1:
# start of loop 1
...
for variable2 in sequence2:
# start of loop 2
...
first line after loop 2
...
continue
...
first line after loop 1
• What line is executed after continue in this example?
– The innermost loop that the continue belongs to is loop 1.
– The next line will be the first line of loop 1 (shown in green).50
Example 1
a = 1
while a <= 10:
# start of loop 1
print("multiples of ", a, ":")
for b in range(1, 11):
# start of loop 2
print(a, "*", b, "=", a*b)
if b == 5:
break
print()
a = a + 1
51
Example 2
a = 1
while a <= 10:
# start of loop 1
print("multiples of ", a, ":")
for b in range(1, 11):
# start of loop 2
print(a, "*", b, "=", a*b)
print()
if a == 5:
break
a = a + 1
52