10 Python conditional loops with while
- Learn about while conditionals and how they are used
10.1 while Loops in Python
A while loop in Python is a control flow statement that allows code to be executed repeatedly based on a boolean condition. The loop continues to execute as long as the condition remains True. Here’s a breakdown of how while loops work:
Key Components
Condition: The loop starts with a condition that is evaluated before each iteration. If the condition is
True, the code block within the loop is executed.Code Block: The statements inside the loop are indented, and these will run repeatedly as long as the condition remains
True.Increment/Decrement: It’s crucial to modify the variable used in the condition within the loop; otherwise, you may create an infinite loop.
Exit: Once the condition evaluates to
False, the loop stops, and the program continues with the next line of code following the loop.
Syntax
while condition:
# Code block to execute
# Update condition variable
Example
Here’s a simple example to illustrate how a while loop works:
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increment count
Explanation of the Example
Initialization: The variable
countis initialized to0.Condition: The
whileloop checks ifcountis less than5.Code Execution: If the condition is
True, it prints the current value ofcount.Increment: The line
count += 1increments the value ofcountby1after each iteration.Termination: Once
countreaches5, the condition becomesFalse, and the loop exits.
This can be incredibly useful in simulations. Or when interacting in the environment. Here the number of iterations is not known beforehand and depend on a certain condition being met. They provide a way to repeat actions and process data dynamically within a program.
However
Infinite Loops: Ensure the condition will eventually evaluate to
Falseto avoid infinite loops.Break Statement: You can use the
breakstatement to exit a loop prematurely if needed.Continue Statement: The
continuestatement can skip the current iteration and proceed to the next one based on a condition.
An example is:
import random
population = 1000
infected = 1
days = 0
infection_rate = 1.5
max_days = 30
while infected < population:
days += 1
if random.random() > 0.9:
print(f"Day {days}: Lockdown in effect, no new infections today.")
continue
new_infections = int(infected * infection_rate)
if new_infections + infected > population:
new_infections = population - infected
infected += new_infections
print(f"Day {days}: {infected} infected.")
if infected >= population:
print(f"Day {days}: The entire population is infected.")
break
if random.random() > 0.8:
print(f"Day {days}: Health measures implemented, slowing infection.")
infection_rate -= 0.3
if infection_rate <= 0.1:
print(f"Day {days}: The infection has nearly stopped spreading.")
break
if days >= max_days:
print("The simulation has reached its time limit.")
break
10.2 Summary
- while loops can be very useful for tasks that do not have a set number of loops allowing simulation and user input
- It is important you do not get infinite loops in your code