Python While Loop Tutorial – While True Syntax Examples and Infinite Loops
While loops are one of the fundamental control flow tools in programming. They allow you to repeatedly execute a block of code as long as a certain condition is met. While loops are incredibly versatile and show up everywhere from simple scripts to complex algorithms.
In this tutorial, we‘ll take an in-depth look at while loops in Python. We‘ll cover the basics of how they work, examine some examples, and learn how to avoid common pitfalls like infinite loops. By the end, you‘ll be able to harness the power of while loops effectively in your own Python programs.
While Loop Basics
A while loop in Python has the following general syntax:
while condition:
# code block
The condition
is an expression that evaluates to either True
or False
. As long as condition
is True
, the code block inside the loop will keep executing repeatedly. Once condition
becomes False
, the loop terminates and execution continues with the next line after the loop.
Here‘s a simple example that prints the numbers 0 to 4:
count = 0
while count < 5:
print(count)
count += 1
This produces the output:
0
1
2
3
4
Let‘s break this down line-by-line:
-
count = 0
initializes a variablecount
to 0. This will act as our loop counter. -
while count < 5:
is the loop condition. It says to keep looping as long as the value ofcount
is less than 5. -
print(count)
is the first line in the loop body. It prints out the current value ofcount
. -
count += 1
incrementscount
by 1 each time through the loop. This is important – without it,count
would always be 0 and the loop would never end! -
When
count
reaches 5, the conditioncount < 5
becomes False and the loop terminates. Execution then proceeds to the next line after the loop (there aren‘t any in this example).
This pattern of initializing a counter, checking a condition, and incrementing the counter is very common in while loops. But while loops are more general than this – the condition can be any expression, and you don‘t necessarily need to use a counter.
Infinite Loops
One pitfall to watch out for with while loops is the dreaded infinite loop. An infinite loop is a loop that never terminates, meaning the condition always stays True no matter what. Your program will get stuck executing the loop forever!
Here‘s an example of an infinite loop:
while True:
print("Hello, world!")
If you run this code, "Hello, world!" will get printed to the console over and over, forever. The program will never stop running on its own. That‘s because the condition is just True
– it‘s always true no matter what, so the loop never terminates.
In most cases, infinite loops are bugs that arise from faulty loop conditions. For instance, let‘s say we forgot the count += 1
line in our previous example:
count = 0
while count < 5:
print(count)
Now count
stays 0 forever and the condition count < 5
is always True. The loop runs indefinitely, printing 0 over and over. Oops!
To stop an infinite loop, you‘ll need to interrupt the program manually. In most terminals, you can do this by pressing Ctrl+C. This sends a special signal to the running program that makes it halt immediately.
However, there are some situations where we actually want a loop to run forever. For instance, the event loop in a GUI application or game should continuously process events and redraw the screen as long as the program is running. How can we do this without writing an infinite loop by accident?
While True Loops
The answer is to use a while True
loop! This is a special syntax in Python that explicitly says you want the loop to run forever. Inside the loop, you can then manually check for any exit conditions and call break
to terminate the loop when needed.
Here‘s the general pattern:
while True:
# loop body
if exit_condition:
break
As long as exit_condition
is False, the loop will keep running. As soon as it becomes True, the break
statement is hit and the loop ends.
Let‘s look at a more concrete example. Say we want to keep prompting the user for input until they enter the word "quit":
while True:
command = input("Enter a command: ")
if command == "quit":
print("Goodbye!")
break
else:
print(f"You entered: {command}")
Here‘s a sample run:
Enter a command: hello
You entered: hello
Enter a command: 123
You entered: 123
Enter a command: quit
Goodbye!
The while True
loop keeps prompting for input forever, but when the user enters "quit", the if
condition becomes True and break
is executed. This terminates the loop and "Goodbye!" is printed.
This pattern of using while True
with break
is very common when you want a loop to run indefinitely until some special termination condition occurs. It‘s much safer than accidentally writing an infinite loop with a faulty condition.
More While Loop Examples
While loops have tons of applications. Here are a few more examples to give you an idea of what‘s possible.
Summing a list of numbers:
numbers = [1, 2, 3, 4, 5]
i = 0
total = 0
while i < len(numbers):
total += numbers[i]
i += 1
print(total) # Output: 15
Implementing a simple guessing game:
import random
number = random.randint(1, 100)
guess = None
num_guesses = 0
while guess != number:
guess = int(input("Guess a number between 1 and 100: "))
num_guesses += 1
if guess < number:
print("Too low, try again!")
elif guess > number:
print("Too high, try again!")
print(f"Congratulations, you guessed it in {num_guesses} tries!")
Finding the first 10 prime numbers:
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
primes = []
num = 2
while len(primes) < 10:
if is_prime(num):
primes.append(num)
num += 1
print(primes) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
While Loop Tips
Here are a few tips to keep in mind when working with while loops in Python:
-
Always make sure your loop condition will become False at some point, unless you‘re using
while True
andbreak
deliberately. Double check your logic to avoid infinite loops. -
Avoid changing the loop counter (e.g.
i
orcount
) inside the loop body, except for the controlled increment at the end. Modifying it elsewhere can lead to unexpected behavior. -
If you need to loop through a sequence like a list or string, consider using a
for
loop instead.for
loops are simpler and less error-prone for iterating over known sequences. -
When using
while True
, make sure you have abreak
statement somewhere to exit the loop. Otherwise, you‘ll still get an infinite loop. -
If your loop body gets long or complex, consider refactoring it into a separate function for better readability.
While Loops vs For Loops
Python has two main types of loops: while
loops and for
loops. While loops are useful when you want to repeat an action until a condition becomes False, but you don‘t necessarily know ahead of time how many iterations will be needed.
For loops, on the other hand, are used to iterate over a known sequence of items, like a list or string. The number of iterations is determined by the length of the sequence.
Here‘s an example of iterating over a list with both a while loop and a for loop:
# While loop version
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
# For loop version
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Both versions produce the same output:
apple
banana
cherry
The for
loop version is much more concise and readable. It‘s the preferred way to iterate over a known sequence in Python.
However, while
loops still have their place. They‘re the go-to choice when you need to repeat an action based on a condition that isn‘t tied to a sequence, or when you don‘t know ahead of time when the loop should stop. You‘ll often see while
loops used for things like input validation, game loops, or implementing algorithms.
Conclusion
While loops are a powerful tool in Python for repeating code blocks based on a condition. They allow you to write programs that adapt and respond to changing conditions at runtime.
In this tutorial, we covered the basics of while
loops, how to use while True
with break
for intentional infinite loops, and looked at some examples of common while
loop patterns. We also discussed some tips for using while
loops effectively and avoiding infinite loops.
To learn more, I highly recommend checking out Python‘s official documentation on while loops. You can also find tons of practice problems online to test your understanding.
With a solid grasp of while
loops in your toolkit, you‘ll be able to write more sophisticated Python programs that can handle all sorts of conditional repetition. Happy coding!