In the last post, we discussed if
statements, which help us skip a part of the code based on a condition. But what if we want to repeat a block of code multiple times? Instead of writing the same statement repeatedly, we use looping statements.
What is a While Loop?
A while
loop in Python is used to execute a block of code repeatedly as long as a given condition is True
. Once the condition becomes False
, the loop terminates.
Syntax of While Loop
while condition:
# Code to execute
A while loop consists of three main parts:
- Initialization: Define where the loop starts.
- Condition: Set a condition that controls the loop.
- Increment/Decrement: Change the variable to eventually break the loop.
Example: Printing Numbers from 1 to 10
Instead of writing 10 print
statements, we can use a while
loop:
i = 1 # Initialization
while i <= 10: # Condition
print(i)
i += 1 # Increment
Example: Printing Numbers from 10 to 1
We can also print numbers in reverse order by decrementing the value:
i = 10 # Initialization
while i > 0: # Condition
print(i)
i -= 1 # Decrement
Infinite Loops
If the loop condition never becomes False
, it runs indefinitely. Be cautious! For example:
i = 1
while i > 0: # Always True condition
print(i)
To avoid this, always ensure the condition eventually turns False
by updating the variable inside the loop.
Using While Loops with Break and Continue
break
: Terminates the loop immediately.
i = 1
while i <= 10:
if i == 5:
break # Stops the loop when i is 5
print(i)
i += 1
continue
: Skips the current iteration and moves to the next.
i = 0
while i < 10:
i += 1
if i == 5:
continue # Skips printing 5
print(i)
When to Use While Loops?
- When the number of iterations is not fixed (e.g., waiting for user input, processing data until a condition is met).
- When continuously monitoring something (e.g., a sensor reading, network connection).
Conclusion
The while
loop is an essential tool in Python for handling repetitive tasks efficiently. By understanding its componentsโinitialization, condition, and increment/decrementโyou can write efficient looping constructs in your programs. Experiment with different conditions and use cases to get comfortable with while
loops!
๐ Stay tuned for more Python basics!
Top comments (1)
contagious stupidity good luck