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:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> finished
finished
> 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:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> finished
finished
> done
Done!
True ?
No
print 'Done'
Yes
break
while True:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
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:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> # don't print this
> print this!
print this!
> 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:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!
True ?
No
print 'Done'
Yes
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
continue
Indefinite Loops
•
While loops are called "indefinite loops" because they keep going until
a logical condition becomes False
•
The loops we have seen so far are pretty easy to examine to see if
they will terminate or if they will be "infinite loops"
•
Sometimes it is a little harder to be sure if a loop will terminate
Does this loop terminate?
•
Collatz Conjecture
inp = raw_input('Enter a Number:')
n = int(inp)
while n != 1 :
print n,
if n % 2 == 0 : # n is even
n = n / 2
else : # n is odd
n = n * 3 + 1
python sequence.py
Enter a Number:3
3 10 5 16 8 4 2
python sequence.py
Enter a Number:16
16 8 4 2
python sequence.py
Enter a Number:50
50 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2
Definite Loops
•
Quite often we have a list of items of the lines in a file - effectively a
finite set of things
•
We can write a loop to run the loop once for each of the items in a
set using the Python for construct
•
These loops are called "definite loops" because they execute an exact
number of times
•
We say that "definite loops iterate through the members of a set"
A Simple Definite Loop
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Không có nhận xét nào:
Đăng nhận xét