CSIT101 Lec3
CSIT101 Lec3
Chapter 5
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
No Yes
while True: True ?
line = input('> ')
if line == 'done' : ....
break
print(line)
print('Done!')
break
...
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
print('Done')
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
No
True ? Yes
while True:
line = input('> ')
....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print(line) ...
print('Done!')
print('Done')
Exercises
1. Write a program that uses a while loop to print numbers from 1 to 10
2. Write a program that asks the user to enter a positive integer N and
then calculates the sum of the first N natural numbers using a while
loop.
3. Write a program that asks the user to enter a number and then uses a
while loop to reverse the digits of the number.
4. Write a program that asks the user to enter a positive integer N and
then calculates the factorial of N using a while loop.
Indefinite Loops
• We can write a loop to run the loop once for each of the items in
a set using the Python for construct
i=2
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.
More Loop Patterns…
Counting in a Loop
$ python countloop.py
zork = 0 Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] : 2 41
zork = zork + 1
print(zork, thing)
3 12
print('After', zork) 43
5 74
6 15
After 6