How to Create a While Loop in Python

Introduction: How to Create a While Loop in Python

There are moments in programming when you need to repeat a set of steps in order to solve a problem. A while loop allows you to loop through a section of code without having to write repeated code. When programming, writing the same code over and over is considered bad practice. You should avoid repeated code to keep your program concise, as well as to make it easier for other programmers to read and interpret your code.

A while loop is a great tool that lets you efficiently loop through a set of steps when programming, while keeping your code clean and concise. The steps below will show you how to create a while loop in Python to loop through a list. This exercise is for beginners who have some knowledge about arrays, which are called “lists” in Python. For this 15 minute exercise, we will loop through a list of numbers and increase each number value by five. For example, if the list has the numbers [1, 2, 4, 7], the loop will produce a new list containing the numbers [6, 7, 9, 12].

Supplies

Python 3 (click the link to download)

Step 1: Define the Function

The first step is to define a function with a parameter that takes in a list. In the example below, a function called addFive is created and given the parameter lst (short for list). Be sure to add a colon at the end of the defined function statement.

def addFive(lst):

Step 2: Initiate an Empty List

Next, we need to initiate an empty list, which we will use to create a new list that will have the increased number values [6, 7, 9, 12] once the function is done running. Placing the values into a new list will allow us to keep the original list unchanged.

In the example below, a new list is created with the variable nlst and, then, set to equal an empty list by typing closed brackets. Make sure to indent the variable.

def addFive(lst):
    nlst = []

Step 3: Set a Variable “index” to the Number 0

We must set a variable index equal to the number 0. This statement establishes the starting index of a list, which is index 0. Later, we will increase index by the number 1 in the while loop to loop through the remaining indexes. See the example below for setting the index variable.

def addFive(lst):
    nlst = []
    index = 0

Step 4: Start While Loop Statement

Next, we will start our while loop by writing the appropriate conditional statement in the example below. We will write our steps for the loop next, after creating the starting statement for the loop. Be sure to include colons at the end of the while loop conditional statement.

def addFive(lst):
    nlst = []
    index = 0
    while index < len(lst):

Let’s breakdown this conditional statement. The statement reads as, “while index is less than the length of the list . . .” The length of the list [1, 2, 4, 7] is equal to 4 because there are 4 number elements in the list. Since a list’s index starts at the number 0, the last index will always be the length of the list minus 1. In our list example [1, 2, 4, 7], the last index of the list is equal to 4 – 1, which equals 3. Therefore, index 3 is the last index in the list.

See the chart above for an example of how indexes align with elements in a list. Index 0 holds the number 1, index 1 holds the number 2, index 2 holds the number 4, and index 3 holds the number 7.

We can see in the chart above how index 3 is the last index in the list. Since index 3 is the last index of the list, we now know that index 3 is the last index that should increase by 5 before ending the while loop. Therefore, we set our while loop conditional statement to keep looping while the variable index is less than the length of the list (4), because the number 3 is one less than the number 4.

Step 5: Add Append Method

Now time to create the body of the loop. For the steps in the body, think about what to do for the first index only. Our while loop will handle repeating the steps for the remaining indexes. In the first index (index 0) of the list [1, 2, 4, 7], we want to take the number 1 and add 5 to it, then add the new number into the empty list nlst.

In order to add an element to an empty list, we have to append the element to the list using the append method. In order to use the append method, we write nlst.append() as shown in the example below, making sure to place parentheses at the end of the method call. Then inside of the parenthesis, we add code that will carry out the addition of the current number element plus 5 (i.e. 1 + 5 = 6).

def addFive(lst):
    nlst = []
    index = 0
    while index < len(lst):
        nlst.append()

Step 6: Insert Math Expression Inside Append

To get the current number element, we access the list element using it’s index like this:

lst[0] = 1

lst[1] = 2

lst[2] = 4

lst[3] = 7

So, to access the first element in the list during the loop, the code would be lst[index] because in the beginning, we set the variable index to 0. To add 5 to the element, we carry out addition by writing lst[index] + 5. For the first index (index 0), this will yield 1 + 5, which equals 6.

Now that we computed the new element number 6, we need to place this number into the empty list nlst by appending it this list. See the below example for the code.

def addFive(lst):
    nlst = []
    index = 0
    while index < len(lst):
        nlst.append(lst[index] + 5)

Step 7: Increase “index” Variable by 1

The next line is simple. Once the new number is computed for index 0, we want to do the same computation for all of the other indexes. Thankfully, the while loop handles running the steps repeatedly until we reach the last index! Now, we just need to make sure the loop selects and computes the next index each time it is done with the current index.

To make the loop select the next index, we simply need to increase the index variable by 1. By increasing the index variable by 1 at the end of each loop, the loop will grab the next index when it runs again. See the example code below for increasing the index variable at the end of the loop.

def addFive(lst):
    nlst = []
    index = 0
    while index < len(lst):
        nlst.append(lst[index] + 5)
        index = index + 1

Step 8: Add a Return Statement

We’ve made it to the final step of creating the while loop function! Now, we simply add a return statement to return the list nlst to any variable we want to set it to. Make sure to un-indent the return statement so that it will ONLY return nlst after the while loop has completely looped through the entire parameter lst.

def addFive(lst):
    nlst = []
    index = 0
    while index < len(lst):
        nlst.append(lst[index] + 5)
        index = index + 1
    return nlst

Step 9: Test the While Loop Function

Now, we just need to test our while loop function to see if it works. First, save your Python file to your computer, then Press F5 on your keyboard to run the program. Next, type the statements in the output example below (the statements that are next to the arrows). Press enter after each statement to see the results.

Your results should match the below outputs. If your results do not match, check to make sure you spelled all of your variables correctly, as misspelled variables are a common mistake when programming. Not correctly spelling a restated variable is a highway to causing error messages when trying to run your code.

>>> a = [1, 2, 4, 7]
>>> b = addFive(a)
>>> b
[6, 7, 9, 12]
>>> a
[1, 2, 4, 7]

*Notice list a remains the same after calling the addFive function. This is because we created a new list in the function body. This is considered a non-destructive function because the original list was NOT destroyed.

Congratulations! You have written your first while loop in Python. A while loop is a great tool that lets you efficiently loop through a set of steps when programming. This loop also helps you write clean code by allowing you to avoid writing repeated code. If you’re ever working on a project with a team, your team members will be thankful for not having to sift through extra lines of unnecessary code when reading your programs. A while loop is a powerful tool that will continue to help you in your coding journey!

Be the First to Share

    Recommendations

    • 3D Printed Student Design Challenge

      3D Printed Student Design Challenge
    • Plastic Challenge

      Plastic Challenge
    • Rocks, Gems, and Stones Speed Challenge

      Rocks, Gems, and Stones Speed Challenge

    Comments