While Loops

A while loop uses a conditional to determine when to exit. The loop must be coded to ensure that the conditional will become False at some point, or it will never terminate.

Python syntax

while conditional:
    block1
else:  #optional
    block2

As for the for loop, colons and indentations are required. The optional else clause is executed if and only if the conditional becomes False, which for a while loop is normal termination.


x=-20
y=-10
while x<0 and y<0:
    x=10-y
    y=y+1
    z=0
print(x,y,z)

Exercise

Modify each for loop in the previous section’s exercise to use a while loop instead.

Example solution

N=10

i=0
while i<=N:
    print(i)
    i+=1

sum_it=0
i=1
while i<=N:
    sum_it+=i
    i+=1

print("The sum of 1 to ",N," is ",sum_it)

Previous
Next