While Loops in Python
While Loops in Python
A while loop in Python allows you to repeatedly execute a block of code as long as a given condition is True. This type of loop is useful when you want to repeat an operation multiple times without knowing in advance how many iterations are needed.
Syntax of a While Loop:
while condition: # Code block to be executedThe condition is evaluated before each iteration of the loop.
If the condition evaluates to
True, the code inside the loop is executed.The loop continues to execute as long as the condition remains
True.If the condition evaluates to
False, the loop terminates, and the program continues with the code after the loop.
1. Basic While Loop Example
Example:
count = 1while count <= 5: print("Count is:", count) count += 1Output:
Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5The loop runs while
countis less than or equal to 5, and the value ofcountincreases by 1 after each iteration.
2. Infinite While Loop
If the condition of the while loop is always True, the loop will run indefinitely (i.e., an infinite loop).
Example of Infinite Loop:
while True: print("This will run forever!") break # To stop the infinite loopHere, the loop would run indefinitely unless there's a way to break out of it. In this case, the
breakstatement is used to stop the loop after one iteration.
3. Using break to Exit the Loop
The break statement is used to exit the loop prematurely when a certain condition is met, even if the loop condition is still True.
Example:
count = 0while count < 10: if count == 5: break # Exit the loop when count is 5 print(count) count += 1Output:
01234The loop stops when
countreaches 5 due to thebreakstatement.
4. Using continue to Skip an Iteration
The continue statement is used to skip the current iteration and move to the next one without executing the remaining code inside the loop.
Example:
count = 0while count < 10: count += 1 if count == 5: continue # Skip printing when count is 5 print(count)Output:
1234678910When
countis 5, thecontinuestatement skips the print and goes back to the top of the loop.
5. While Loop with Else
A while loop can also have an else block, which is executed when the loop condition becomes False. The else block is not executed if the loop is terminated using a break.
Example:
count = 1while count <= 5: print("Count is:", count) count += 1else: print("Loop has ended.")Output:
Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5Loop has ended.The
elseblock is executed after the loop finishes, but it will not execute if the loop is exited viabreak.
6. Nested While Loops
You can have a while loop inside another while loop. This is known as a nested loop.
Example:
i = 1while i <= 3: j = 1 while j <= 2: print(f"i = {i}, j = {j}") j += 1 i += 1Output:
i = 1, j = 1i = 1, j = 2i = 2, j = 1i = 2, j = 2i = 3, j = 1i = 3, j = 2Here, for each value of
i, the innerwhileloop runs forjvalues from 1 to 2.
7. Practical Example:
A practical example of a while loop is when asking the user to input a valid value until the user provides the correct input.
Example:
while True: user_input = input("Enter a number between 1 and 10: ") if user_input.isdigit(): number = int(user_input) if 1 <= number <= 10: print(f"Valid number: {number}") break else: print("The number must be between 1 and 10.") else: print("Please enter a valid number.")This loop keeps asking the user for a number until a valid number between 1 and 10 is provided.
8. Conclusion
whileloops are used to execute a block of code repeatedly as long as a specified condition isTrue.They are useful when you don't know beforehand how many times you need to repeat a task.
You can control the flow of a
whileloop with statements likebreak,continue, andelse.It's important to ensure that the loop condition eventually becomes
Falseto prevent infinite loops, unless intentionally required.
Understanding how to use while loops effectively can significantly improve the flexibility of your Python programs.