How to Create a While Loop in Python
Computers are much better than people at performing repetitive tasks over and over. You may have a large (and sometimes infinite) list of programmatic tasks that you wish to do, and while loops in Python allow you to perform them without having to cut and paste and modify large blocks of code repeatedly.
Instructions
-
Create a While Loop
-
1
Create a conditional statement to be checked by the while loop. This conditional statement is checked over and over again by Python to see if it is true.
-
2
Realize that while the conditional statement is true, the code inside the body of the while loop will continue to execute. Using the following example:
i = 0
while i < 5:
In the above, we declare a variable i to initially be zero. The next line is the beginning of the while loop, where we say we want a loop to occur repeatedly while the value of i is less than 5. -
-
3
Determine how you will terminate the loop. The while loop will execute until the conditional statement is false.
-
4
Realize that any variables used in the conditional statement can also be changed inside the while loop while it is running. In this example, you will simply add one to the variable i each time you go through the loop:
i = 0
while i < 5:
i = i + 1 -
5
Perform any other tasks you wish to repetitively occur while the loop is running:
i = 0
while i < 5:
i=i+1
print 'value of i is", i
This example will print:
value of i is 1
value of i is 2
value of i is 3
value of i is 4
value of i is 5
-
1
Tips & Warnings
You can create a loop that goes on forever (an infinite loop), by having an evaluation clause that is always true. For example: "while True:" will loop inexhaustibly.
If you wish to leave a loop early (especially in the case of an infinite loop), you can use the break statement to terminate the loop.
If you wish to skip a step or two in the loop, you can use Python's continue statement. This statement will cause the code to jump to the "top" of the loop without executing any of the body associated with it.
Resources
Comments
-
Srinivas Kulkarni
Nov 25, 2010
how to