IntroductionMany times in programming, you will need to repeat the same task many times. In fact, looping through and repeating an operation is one of the cornerstones of programming. After all, one of the things that computers are way better than humans at is performing repetitive tasks without getting tired or making mistakes.
One of the simplest ways to make a program repeat the same task is to use a
whileloop repeats the same block of code while a condition is true. When that condition becomes false, the loop will break, and the regular flow of code will resume.
The structure of a
whileloop is similar to what you encountered in the last guide with
if. A while loop begins with the word
whilefollowed by parenthesis containing the condition of the loop and a colon. The following lines are indented and will execute in the loop.
Infinite WhileCheck out this while loop. Try it yourself in your interpreter to see exactly what it does. You might be somewhat surprised.
# Import time for sleep import time # While loop while(True): print("looping...") time.sleep(2)What happened? Rather, what is happening? If you haven't figured out how to stop it yet, just press
whileloop will run indefinitely as long as the condition that it is given remains
True. The loop above was given
Trueas its condition, which will never not be true.
Occasionally, you will need to run an infinite loop. They are useful for things like monitoring data for changes. If that is the case, passing
Trueis a sure fire way to do that.
There is another piece of this puzzle.
sleep()is a method that causes Python to pause for a specified number of seconds. Give
sleep()the number of seconds that you want it to pause for in its parenthesis, and it will stall the execution of your program. It's fairly common to see
sleep()in loops, especially infinite ones.
Counting DownOne way to stop a
whileloop is to use a counting variable. Set the condition of the loop to the number where you want the loop to stop iterating, and increment the counting variable every time the loop runs.
count = 0 while(count < 10): print("loop number: %d" % (count + 1)) count += 1The
countvariable starts off as zero. The condition specified to the loop states that it will run as long as
countis less than ten. It will not run while count is ten. Notice that the loop runs ten times, though. That's because the loop runs while
countequals zero. The output is able to say that the first run is number one and the last is ten because the variable being substituted in to the string is
count + 1, so it displays one more than the current count value. After the
print(), one is added to
BreakYou can also break a
whileloop from inside the loop using
break. It usually works best in conjunction with
if, and a specific circumstance that would cause an otherwise endless loop to break.
# Import Random for random number generator import random # Infinite while loop with break condition while(True): num = random.randint(1, 10) print(num) if(num == 7): print("Stopping...") break else: print("Still looping...")The loop is set up to run indefinitely by passing
Trueas the condition of the loop. However, there is a condition in which the loop can break. If the variable
numis equal to seven during one of the iterations, the code will arrive at
breakand break the loop.
This example isn't entirely realistic. The random library was imported, and a random number generator was used to create the value of
numon each iteration. That particular code
random.randint(1, 10), is a method from the random library that chooses a random number between one and ten. The range can be specified by changing the start and end numbers. In a real world scenario, it would probably be user input or a signal from another part of the program that would break the loop. In fact, infinite loops like this are often used to listen for user input.
ConclusionWhile loops are one of the most important tools in repeating operations in Python. They can be used to iterate a set number of times, until a signal or condition is met, or indefinitely. While their structure is very simple, it is important to keep track of what is in the loop and exactly when it is supposed to end. It is very easy to allow one of these
whileloops get away from you. In improperly constructed loop can cause excessive resource usage, hanging, and in incorrect program flow. Just make sure to keep an eye on the path your loop is taking.
Table of Contents
- Python Introduction and Installation Guide
- Python Files and the Interpreter
- Experimenting With Numbers and Text In Python
- Python Variables
- Working With Number Variables In Python
- Python String Basics
- Advanced Python Strings
- Python Comments
- Python Lists
- Python List Methods
- Python Multidimensional Lists
- Python Tuples
- Python Boolean Operators
- Python If Statements
- Python While Loops
- Python For Loops
- Python Dictionaries
- Python Advanced Dictionaries
- Python Functions