knowledge-kitchen / course-notes

Loops - Recap (in Python)

For loops

For loops iterate through a finite sequence of values.

Iterate through strings, lists, ranges, or files:

For loop flow chart

While loops

While loops repeat a potentially unfinite number of iterations.

While loop flow chart

General loop controls

Input validation

Flags/sentinels

Formatting

Example programs in Python

Number validation example

Note the use of the while loops to indefinitely iterate until an acceptable number has been entered.

msg = "What's your lucky integer"

num = ""

while not num.isnumeric():
    num = input(msg)

num = int(num)

while num != 50:
    print("Sorry, that's not right.")
    num = int(input("What's your favorite number?"))

Name validation example

Note the use of the while loop to indefinitely iterate until an acceptable name has been entered.

name = input("What's your name").lower()

while not name == "bob":
   name = input("What's your name?")

print("Hi Bob!")

Running total example

Note the use of a flag, the accumulator pattern, and the while loop

hoursTotal = 0

keepLooping = True #start the flag as true

#keep looping as long as the flag is true
while keepLooping:

    #set the starting point of our variable to make the loop kick in
    num = "foo"

    while not num.isnumeric():
        num = input("Please enter a number of hours:")
        if num.lower() == "stop":
            keepLooping = False #set the flag to false
            break #break out of immediate while loop

    #if the user entered stop, break out of the main while loop
    if not keepLooping:
        break

    #this only executes if the user entered a number
    num = int(num)

    hoursTotal = hoursTotal + num


print("You worked " + str(hoursTotal) + " hours total")