If you just landed here, looking for help on Python training, or Python looping you came to the right spot! If your new to Python programming, you might start back on my first post before hopping into a discussion of loops.

Before reading about my take on Python looping, start by reviewing the official documentation on Python while loops, and Python for loops. After you read over what Python.org has to say on the matter, it is time to start coding.

Lab 4.1 – Using a while loop

I have long thought writing simple games a fun way to learn programming. Imagine a simple text parser. The interface must prompt the user for some kind of input. Perhaps one of the simplest situations to code for, is the user simply hitting ENTER without typing anything

In the code below, usercommand is an empty string, until the user types anything and sets the variable otherwise. If they do not type anything, and simply hit ENTER, then they will remain ‘stuck’ within the loop, continually prompted for input by the alligator mouth >

Try running the code below:

#!/usr/bin/python3
"""Russell Zachary Feeser - https://rzfeeser.com
    while looping - loopdeyloops01.py"""

def main():
    """run-time code"""

    # Print an intro and new line    
    print("Welcome to RZFeeser's Python Training Adventure!\n")

    # set usercommand to an empty string
    usercommand = ""

    # print instructions
    print("Enter a command:")
    # create a conditional loop
    # the only way to exit this loop
    # is to provide a value to usercommand
    # if the user JUST hits ENTER, they will remain within the loop
    while usercommand == "":
        usercommand = input("> ")

    # consider the user's input
    # first split the input into a list along white space boundaries
    # then select the 0th value
    # and IF that value is equal to the string "go", THEN...
    if usercommand.split()[0] == "go":
        print("You walk to the", usercommand.split()[1])
    else:
        print("That is not a valid command")

if __name__ == "__main__":
    main()

Try running the above code. Just hit ENTER a few times. Now type, go east, followed by go west. Pretty cool, right? Keep reading, and we’ll improve our game logic.

Lab 4.2 – Using a while true loop with break

One of the problems with the above code is that it only allows the user to take a ‘single’ turn. One fix, nest the above code within a while True loop, to allow the user to repeat making input. We want to ensure this will include ‘resetting’ usercommand to an empty string at the top of each ‘turn’.

The problem with a white True loop, is that while True is always True. In effect, we’ve created an infinite loop. Therefore, we should give the user a way to ‘break’ out. When encountered, the break statement, ‘breaks’ out of whatever loop you might current be operating within.

#!/usr/bin/python3
"""Russell Zachary Feeser - https://rzfeeser.com
    while looping - loopdeyloops02.py"""

def main():
    """run-time code"""

    # Print an intro and new line    
    print("Welcome to RZFeeser's Python Training Adventure!\n")

    while True:
        # set usercommand to an empty string
        usercommand = ""

        # print instructions
        print("Enter a command:")
        # create a conditional loop
        # the only way to exit this loop
        # is to provide a value to usercommand
        # if the user JUST hits ENTER, they will remain within the loop
        while usercommand == "":
            usercommand = input("> ")
        
        # test if usercommand was 'exit'
        if usercommand.lower() == 'exit':
            break
  
        # consider the user's input
        # first split the input into a list along white space boundaries
        # then select the 0th value
        # and IF that value is equal to the string "go", THEN...
        if usercommand.split()[0] == "go":
            print("You walk to the", usercommand.split()[1])
        else:
            print("That is not a valid command")

    # outside of the while True loop
    # the user typed 'exit'
    print("Thanks for playing!")
if __name__ == "__main__":
    main()

Lab 4.3 – Using while counting loop

We could take the above code a step further, and add a counter inside of our while True loop, which could serve to illustrate the ‘turn’ a user is currently on.

#!/usr/bin/python3
"""Russell Zachary Feeser - https://rzfeeser.com
    while looping - loopdeyloops03.py"""

def main():
    """run-time code"""

    # Print an intro and new line    
    print("Welcome to RZFeeser's Python Training Adventure!\n")


    # define user counter
    userturn = 0

    while True:
        # set usercommand to an empty string
        usercommand = ""

        # increase userturn by 1
        userturn += 1   # <-- shorthand for # userturn = userturn + 1

        # print instructions
        print("Turn:", userturn, "\nEnter a command:")
        # create a conditional loop
        # the only way to exit this loop
        # is to provide a value to usercommand
        # if the user JUST hits ENTER, they will remain within the loop
        while usercommand == "":
            usercommand = input("> ")
        
        # test if usercommand was 'exit'
        if usercommand.lower() == 'exit':
            break
  
        # consider the user's input
        # first split the input into a list along white space boundaries
        # then select the 0th value
        # and IF that value is equal to the string "go", THEN...
        if usercommand.split()[0] == "go":
            print("You walk to the", usercommand.split()[1])
        else:
            print("That is not a valid command")

    # outside of the while True loop
    # the user typed 'exit'
    print("Thanks for playing!")
if __name__ == "__main__":
    main()

Lab 4.4 – Using a for loop

The above ‘game’ assumes an infinite number of turns. Suppose we wanted to limit the number of turns a user might take? In that case, a while True loop might be the wrong choice. Instead, it might make more sense to reach for a loop that ‘iterates’ (fancy word for counts) across a collection.

In the example below, the while true logic has been replaced by a for loop that counts across the range(1,11), which is a fancy way of saying, “Hey python, count from 1 to 10 (don’t include 11). And use the default step of 1”. The step can be controlled by including a third integer. For example, if you wanted to count by two, you could supply, range(1,11,2).

Our game now starts at turn 1, and marches up to turn 11. Therefore, we no longer need to increase our counter each turn.

#!/usr/bin/python3
"""Russell Zachary Feeser - https://rzfeeser.com
    while looping - loopdeyloops04.py"""

def main():
    """run-time code"""

    # Print an intro and new line    
    print("Welcome to RZFeeser's Python Training Adventure!\n")

    for userturn in range(1,11):
        # set usercommand to an empty string
        usercommand = ""

        # print instructions
        print("Turn:", userturn, "\nEnter a command:")
        # create a conditional loop
        # the only way to exit this loop
        # is to provide a value to usercommand
        # if the user JUST hits ENTER, they will remain within the loop
        while usercommand == "":
            usercommand = input("> ")
        
        # test if usercommand was 'exit'
        if usercommand.lower() == 'exit':
            break
  
        # consider the user's input
        # first split the input into a list along white space boundaries
        # then select the 0th value
        # and IF that value is equal to the string "go", THEN...
        if usercommand.split()[0] == "go":
            print("You walk to the", usercommand.split()[1])
        else:
            print("That is not a valid command")

    # outside of the while True loop
    # the user typed 'exit'
    print("Thanks for playing!")
if __name__ == "__main__":
    main()

If Python looping with while or for is confusing, make a comment below concerning what has you ‘stuck’ and I’ll be sure to follow up, or fix this post. Thanks for reading!

You: “I need a seasoned Python trainer with real world experience that can be on-site…”

If you landed here because you’re searching for a Python Subject Matter Expert (SME), then you’re on the right track! For the past decade I’ve been training telecoms on the evolution of 3G to 4G LTE and now, 5G. In addition to understanding VoIP very well, I’ve been coding since I was just a little guy. I regularly lead training events all around the globe, and would like to provide your next training solution.

All courses can be tailored to fit your group’s ability level. If the goal is to automate, we can even focus our discussions on the vendor(s) within your network! Some of my courses include:

  • Introduction to Python (4 days)
  • Automating with Python (4 days)
  • Introduction to Automating with Ansible (4 days)
  • Programming Ansible with Python (4 days)
  • Expanding Server Operations with Ansible and Python (4 days)
  • Ansible for Dell EMC PowerMax Flash Storage Array (3 days)
  • Ansible for Palo Alto Firewalls (3 days)

Contact me directly through my website, or shoot me an email, for pricing and availability.