Python 3

home

Introduction to Python

davidbpython.com




The 'while' Statement and Looping

the concept of incrementing

We reassign the value of an integer to effect an incrementing.


x = 0         # int, 0

x = x + 1     # int, 1
x = x + 1     # int, 2
x = x + 1     # int, 3

print(x)      # 3

For each of the three incrementing statements above, a new value that equals the value of x is created, and then assigned back to x. The previous value of x is replaced with the new, incremented value. Incrementing is most often used for counting within loops -- see next.





while loops

A while test causes Python to loop through a block repetitively, as long as the test is True.


This program prints each number between 0 and 4

cc = 0                 # initialize a counter

while cc < 5:          # "if test is True, enter the block"
    print(cc)
    cc = cc + 1        # "increment" cc:  add 1 to its current value
                       # WHEN WE REACH THE END OF THE BLOCK,
                       # JUMP BACK TO THE while TEST

print('done')

The block is executing the print and cc = cc + 1 lines multiple times - again and again until the test becomes False. Of course, the value being tested must change as the loop progresses - otherwise the loop will cycle indefinitely (infinite loop).





understanding while loops

while loops have 3 components: the test, the block, and the automatic return.


cc = 10

while cc > 0:         # the test (if True, enter the block)

       print(cc)      # the block (execute as regular Python statements)
       cc = cc - 1

  # the automtic return [invisible!]
  # (at end of block, go back to the test)

print('done')





loop control: "break"

break is used to exit a loop regardless of the test condition.


xx = 0
while xx < 10:
    answer = input("do you want loop to break? ")
    if answer == 'y':
        break             # drop down below the block
    print('Hello, User')
    xx = xx + 1
    print('I have now greeted you ' + str(xx) + ' times')

print("ok, I'm done")




loop control: "continue"

The continue statement jumps program flow to next loop iteration.


x = 0
while x < 10:
    x = x + 1
    if x % 2 != 0:             # will be True if x is odd
        continue               # jump back up to the test and test again
    print(x)

Note that print(x) will not be executed if the continue statement comes first. Can you figure out what this program prints?





the "while True" loop

while with True and break provide us with a handy way to keep looping until we feel like stopping.


while True:
    var = input('please enter a positive integer:  ')
    if int(var) > 0:
        break
    else:
        print('sorry, try again')

print('thanks for the integer!')

Note the use of True in a while expression: since True is always True this test will be always be True, and cause program flow to enter (and re-enter) the block. Therefore the break statement is essential to keep this loop from looping indefinitely.





debugging loops: the "fog of code"

Use print() statements to give visibility to your code execution.


The output of the code should be the sum of all numbers from 0-10, or 55:

revcounter = 0
while revcounter < 10:

    varsum = 0
    revcounter = revcounter + 1
    varsum = varsum + revcounter

    print("loop iteration complete")
    print("revcounter value: ", revcounter)
    print("varsum value: ", varsum)
    input('pausing...')
    print()
    print()

print(varsum)                        # 10

I've added quite a few statements, but if you run this example you will be able to get a hint as to what is happening:

loop iteration complete
revcounter value:  1
varsum value:  1
pausing...                          # here I hit [Return] to continue


loop iteration complete
revcounter value:  2
varsum value:  2
pausing...                          # [Return]

So the solution is to initialize varsum before the loop and not inside of it:

revcounter = 0
varsum = 0
while revcounter < 10:

    revcounter = revcounter + 1
    varsum = varsum + revcounter

print(varsum)

This outcome makes more sense. We might want to check the total to be sure, but it looks right. The hardest part of learning how to code is in designing a solution. This is also the hardest part to teach! But the last thing you want to do in response is to guess repeatedly. Instead, please examine the outcome of your code through print statements, see what's happening in each step, then compare this to what you think should be happening. Eventually you'll start to see what you need to do. Step-by-baby-step!





[pr]