Python Concepts/While Statement
Objective
[edit | edit source]
|
Lesson
[edit | edit source]
The While Statement[edit | edit source]Although the >>> pop = 0
>>> while pop != 5:
... pop += 1
... print(pop)
...
1
2
3
4
5
>>> eggs = [12, 4, 2, 6, 11, 23]
>>> while eggs:
... print(eggs[0])
... del eggs[0]
...
12
4
2
6
11
23
>>> while False:
... print("This will never print!")
...
>>> spam = 10
>>> while spam:
... spam -= 1
... print(spam)
...
9
8
7
6
5
4
3
2
1
0
The Else Statement[edit | edit source]Unlike a lot of other computer languages, Python allows you to use an >>> spam = 0
>>> while spam != 10:
... spam += 1
... print(spam)
... else:
... print("Done printing spam!")
...
1
2
3
4
5
6
7
8
9
10
Done printing spam!
>>> while True:
... pass
... else:
... print("I'll never get seen on the screen!")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The Break Statement[edit | edit source]There can be times when you want to prematurely end a >>> pop = 0
>>> while True:
... print(pop)
... pop += 1
... if pop == 10:
... break
...
0
1
2
3
4
5
6
7
8
9
Continue Statement[edit | edit source]Although the >>> bacon = 0
>>> while bacon != 10:
... bacon += 1
... if bacon < 5:
... continue
... print(bacon)
...
5
6
7
8
9
10
|
Detecting Abnormal Termination
[edit | edit source]
If the x = 11 ; normalTermination = False
while x :
x -= 1
if x < 5 : continue
print (x)
else :
normalTermination = True
if normalTermination :
print ('normal termination')
else:
print ('abnormal termination')
10 9 8 7 6 5 normal termination
x = 11 ; normalTermination = False
while x :
x -= 1
if x < 5 : break
print (x)
else :
normalTermination = True
if normalTermination :
print ('normal termination')
else:
print ('abnormal termination')
10 9 8 7 6 5 abnormal termination "Normal" termination[edit | edit source]The following code produces four examples of "Normal" termination: for c in [-4,0,3,19] :
print ('\ninitial c =', c)
while 5 > c >= 0 :
print ('c =', c)
c += 1
else :
print ('normal termination. c =', c)
initial c = -4 normal termination. c = -4 initial c = 0 c = 0 c = 1 c = 2 c = 3 c = 4 normal termination. c = 5 # This is probably what you wanted. initial c = 3 c = 3 c = 4 normal termination. c = 5 initial c = 19 normal termination. c = 19 The following code also produces "Normal" termination: c = 0
print ('\ninitial c =', c)
while 5 > c >= 0 :
print ('c =', c)
c += 1
if c == 4 : c += 234 # to simulate c becoming corrupted
else :
print ('normal termination. c =', c)
initial c = 0 c = 0 c = 1 c = 2 c = 3 normal termination. c = 238 For normal termination we expect for c in [-4,0,3,19] :
print ('\ninitial c =', c)
while 5 > c >= 0 :
print ('c =', c)
c += 1
else :
if c == 5 : print ('normal termination. c =', c)
initial c = -4 initial c = 0 c = 0 c = 1 c = 2 c = 3 c = 4 normal termination. c = 5 initial c = 3 c = 3 c = 4 normal termination. c = 5 initial c = 19 Even this code is not fool-proof. Try again: for c in [-4,0,3,19] :
print ('\ninitial c =', c)
count = 0
while 5 > c >= 0 :
print ('c =', c)
c += 1
count += 1
else :
if c == count == 5 : print ('normal termination. c =', c)
initial c = -4 initial c = 0 c = 0 c = 1 c = 2 c = 3 c = 4 normal termination. c = 5 initial c = 3 c = 3 c = 4 initial c = 19 You can see that controlling the performance and behavior of loops is not a trivial matter. The [edit | edit source] |
Nested while
statements
[edit | edit source]
a = 0
while a < 10 :
b = 0
while b < 10 :
c = 0
while c < 10 :
print ('{}{}{}'.format(a,b,c))
pass
c += 1
b += 1
a += 1
else:
print ('normal termination')
000 # 001 # ... # 1000 numbers from 000 through 999 998 # 999 # normal termination In the body of the innermost a = 0 ; flag = True
while a < 10 and flag :
b = 0
while b < 10 and flag :
c = 0
while c < 10 :
print ('{}{}{}'.format(a,b,c))
if a ==2 and b == 4 and c == 3 : flag = False ; break
c += 1
b += 1
a += 1
else:
print ('normal termination')
print ('flag =', flag)
000 # 001 # ... # 244 numbers from 000 through 243 242 # 243 # normal termination flag = False # This indicates abnormal termination.
class label(Exception): pass # declare a label
try:
a = 0
while a < 10 :
b = 0
while b < 10 :
c = 0
while c < 10 :
print ('{}{}{}'.format(a,b,c))
# if a ==2 and b == 4 and c == 3 : raise label() # goto label
# if a ==2 and b == 4 and c == 3 : raise KeyError
if a ==2 and b == 4 and c == 3 : 1/0 # force an error, divide by 0.
c += 1
b += 1
a += 1
else:
print ('normal termination')
except label: # where to goto
print ('took exception')
except ZeroDivisionError :
print ('ZeroDivisionError')
except ValueError :
pass
except KeyError :
print ('KeyError')
except :
print ('unknown')
000 001 002 .... 241 242 243 ZeroDivisionError The |
Programming style
[edit | edit source]
Avoid hidden endless loops such as: a = 2
while a != 9 :
pass
a += 2
or a = 2
while a < 30 :
pass
a += b # what if b is always negative?
or a = 2
while a < 30 :
if a > 20 : continue
pass
a += 1
Avoid loops that will never iterate: a = 2
while (a % 5) == 3 :
pass
a += 1
else :
print ('Normal termination.')
In some of the examples above the incrementer was at the bottom of the loop: c = 0
while c < 10 :
print ('c =', c)
pass
pass
pass
c += 1
As the body of the loop gets bigger, the importance of the incrementer remains but becomes less obvious. The following code with the incrementer at the top does the same job: c = -1
while c + 1 < 10 :
c += 1
print ('c =', c)
pass
pass
pass
With the incrementer at the top you can put more code into the body of the loop without having to consider the incrementer.
c = 0
pass
pass
if c == 0 :
while c < 5 :
print ('c =', c)
pass # Be careful not to call a function here that might change 'c'.
c += 1
else :
if c == 5 : # This is a necessary (but insufficient) test for normal termination of this loop.
print ('Normal termination') # "Normal termination" means normal termination of the loop.
# It does not mean normal termination of the job.
else :
print ('initial value of c', c, 'not acceptable for this loop.')
c = 0 c = 1 c = 2 c = 3 c = 4 Normal termination
|
Examples
[edit | edit source]
Given p = 0
while p < len(a):
if a[p] < 0 : del a[p]
p += 1
print ('a =', a)
Take care when code in the body of the loop changes a condition of the loop. Reverse the order of test and delete, and you can ignore whatever may have happened behind you: a = [0,1,-2,3,-4,-5,-6,-7,8,-9,10,11,-12]
p = len(a) - 1
while p >= 0 :
if a[p] < 0 : del a[p]
p -= 1
print ('a =', a)
conditionFound = True
while True :
if a == condition1 :
pass; pass; etc
break
if a == condition2 :
pass; pass; etc
break
if a == condition3 :
pass; pass; etc
break
conditionFound = False ; break
|
Assignments
[edit | edit source]
|
Further Reading or Review
[edit | edit source]
|
References
[edit | edit source]
1. Python's documentation: "3.2. First Steps Towards Programming", "4.4. break and continue Statements, and else Clauses on Loops", "5.6. Looping Techniques", "7.9. The break statement", "7.10. The continue statement", "8.2. The while statement"
|