Python While Loops

Introduction

Many 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 while loop. A while loop 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 while loop is similar to what you encountered in the last guide with if. A while loop begins with the word while followed by parenthesis containing the condition of the loop and a colon. The following lines are indented and will execute in the loop.

Infinite While

Check 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 Ctrl+C. A while loop will run indefinitely as long as the condition that it is given remains True. The loop above was given True as 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 True is 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 Down

One way to stop a while loop 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 += 1

The count variable starts off as zero. The condition specified to the loop states that it will run as long as count is 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 count equals 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 count.

Break

You can also break a while loop 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 True as the condition of the loop. However, there is a condition in which the loop can break. If the variable num is equal to seven during one of the iterations, the code will arrive at break and 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 num on 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.

Conclusion

While 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 while loops 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

  1. Python Introduction and Installation Guide
  2. Python Files and the Interpreter
  3. Experimenting With Numbers and Text In Python
  4. Python Variables
  5. Working With Number Variables In Python
  6. Python String Basics
  7. Advanced Python Strings
  8. Python Comments
  9. Python Lists
  10. Python List Methods
  11. Python Multidimensional Lists
  12. Python Tuples
  13. Python Boolean Operators
  14. Python If Statements
  15. Python While Loops
  16. Python For Loops
  17. Python Dictionaries
  18. Python Advanced Dictionaries
  19. Python Functions


Comments and Discussions
Linux Forum