Python Introduction | Statements | Repeating with a while Condition

Another important control structure is repetition. Python provides two looping statements. The first is while, which checks a condition.

Basic while Statement 1

while condition:
    repeated process ......

Basic while Statement 2

while condition:
    repeated process ......
else:
    process after the loop ......

The condition works like the condition in an if statement. It is an expression, variable, or value evaluated as True or False.

A while statement checks its condition and repeatedly executes its body while the condition is True. When the condition becomes False, the loop ends and execution continues. If an else block is present, Python executes it when the loop finishes.

Consider the following example.

x = 100
count = 1
total = 0
while count <= x: 
    total = total + count 
    count = count + 1
else: 
    print(str(x) + "까지 합계는 " + str(total) +"이다.") 
print(".....end.")

This example calculates and displays the sum from 1 through x. Change the value of x and inspect the results.

The condition is while count <= x:. The loop continues while count is less than or equal to x and ends when count becomes greater than x.

The value of count must increase during the loop. Otherwise, the while loop never finishes. This is called an infinite loop. When using while, consider both the condition and how values change during repetition.