Python While Loops
In Python, a while loop is used to repeatedly execute a block of code as long as a certain condition remains true. It’s an essential control structure for creating loops in your programs.
Basic Structure:
while condition:
# Code to be executed while the condition is trueExplanation:
- The loop starts by checking the condition.
- If the condition is
True, the code block inside the loop is executed. - After executing the code block, the condition is checked again.
- If the condition is still
True, the loop continues to execute. This process repeats until the condition becomesFalse. - When the condition becomes
False, the loop terminates, and the program continues with the next statement after the loop.
Example 1: Python while loops program for Counting from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1In this example, the loop starts with count equal to 1. It prints the value of count, increments it by 1, and repeats the process until count is no longer less than or equal to 5.
Get v_code’s stories in your inbox
Join Medium for free to get updates from this writer.
Example 2: Python While loop program for User Input Validation:
user_input = input("Enter 'yes' to continue: ")
while user_input != 'yes':
user_input = input("Please enter 'yes' to continue: ")In this example, the program asks the user to enter ‘yes’ to continue. The loop continues to prompt the user until ‘yes’ is entered. This is a common use case for input validation.
Example 3: Python while loop program for Sum of Numbers:
total = 0
num = 1
while num <= 10:
total += num
num += 1
print("Sum of numbers from 1 to 10:", total)This loop calculates the sum of numbers from 1 to 10. It starts with total and num both initialized to 0 and 1, respectively. The loop keeps adding num to total and incrementing num until num is no longer less than or equal to 10.
These examples should help you understand the basics of while loops in Python. They are commonly used for tasks that need to be repeated until a certain condition is met. Be careful to ensure that the condition eventually becomes False to avoid infinite loops.






