Python 3

home

Introduction to Python

davidbpython.com




The while Block Statement and Looping Blocks


the concept of incrementing

Incrementing means increasing by one.


x = 0         # int, 0

x = x + 1     # int, 1
x = x + 1     # int, 2     (can also say x += 1)
x = x + 1     # int, 3

print(x)      # 3






while looping block

A while block with a 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; if False, drop below
    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 (cc) must change as the loop progresses - otherwise the loop will cycle indefinitely (infinite loop).






understanding while looping blocks

while loop statements 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 AUTOMATIC 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
print('Hello, User')

while xx < 10:

    answer = input("do you want the loop to break? ")

    if answer == 'y':
        break                  # drop down below the block

    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?


2
4
6
8
10





the while True looping block

while with True and break provide us with a handy way to keep looping until we wish to stop, and at any point in the block.


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, the if test will be always be True, and will cause program flow to enter (and re-enter) the block every time execution returns to the top. Therefore the break statement is essential to keep this block from looping indefinitely. ex 3.17 - 3.22






debugging loops: the "fog of code"

What do we do when we get bad output, but with no error messages?


The output of the code should be the sum of all numbers from 0-10 (i.e. 55), but instead it is 10:

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

Why is it not working? You may see it right away, but I'd like you to imagine that this code is a lot more complicated, such that it won't be easy to see the reason. And you may be tempted to tinker with the code to see whether you can get the correct output, but it's important to understand that we need to be more methodical. We do this with print() statements.





[pr]