C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Less than 10: This while-loop continues as long as the variable i has a value less than 10 when the statement is encountered.
And: After each iteration, the variable i has 2 added to it. When it reaches the value 8, the condition in the while evaluates to false.
Finally: And the loop body is not executed any more. The number 10 is never printed.
Python program that shows while-loop
i = 0
# While loop condition.
while i < 10:
print(i)
# Add two.
i += 2
Output
0
2
4
6
8
But: The loop only executes when it is greater than 100. The statements within the while are not reached.
So: We can use the else-statement, after the main part of a while-loop, to catch these situations.
Python program that shows while-else
i = 0
# While loop condition.
while i > 100:
print(i)
# Subtract two.
i -= 2
else:
print("Loop not entered")
Output
Loop not entered
It stops: No further iterations execute. The condition in the while-loop makes no difference.
Here: The while-loop keeps iterating until the value of "i" is evenly divisible by 7. Then we break.
Python program that uses break
i = 10
# While greater than zero.
while i >= 0:
print(i)
# End loop if evenly divisible by seven.
if i % 7 == 0:
break
i -= 1
Output
10
9
8
7
Caution: A while-true loop can cause serious trouble. If you do not break, it will indefinitely continue.
True: The True constant must be specified with an uppercase first letter in Python.
Random: This program uses the randint method from the random module. This method returns a number between (and including) 0 and 100.
RandomPython program that uses while True
import random
# A while-true loop.
while True:
n = random.randint(0, 100)
print(n)
# Break on even random number.
if n % 2 == 0:
break
Output
41
13
99
18
But: In Python, we use no semicolons. Instead, we use the pass statement to have an empty loop body.
Tip: The pass statement can also be used in def-method bodies, or lambda expressions.
passPython program that uses pass
import random
def m():
# Get random number.
n = random.randint(0, 3)
print(n)
# Return true if number is less than 3.
return n <= 2
# Call method until it returns false.
while m():
# Do nothing in the loop.
pass
Output
0
2
2
3
Sometimes: It is easier to use a continue statement instead of an else statement. In some blocks, this makes code easier to read.
And: The continue statement can help improve loop symmetry in loops that also use the break statement.
Python program that uses continue statement
list = ["cat", "dog", "panther", "parakeet"]
i = 0
while i < len(list):
element = list[i]
i += 1
# Test for this element.
if element == "panther":
continue
# Display element.
print("Pet", element)
Output
Pet cat
Pet dog
Pet parakeet
Program: We continue looping until we acquire a random number that is odd. We use a modulo division to find an odd (not even) number.
Python program that uses while loop, gets random numbers
import random
while True:
# Get random int.
n = random.randint(0, 100)
print("RANDOM", n)
if n % 2 != 0:
print("ODD")
break
Output
RANDOM 54
RANDOM 64
RANDOM 53
ODD
Here: The valid_number and handle_number functions control both parts of the while-loop. The text "Hello friend" is printed.
Python program that uses while, one-line functions
def valid_number(i): return i <= 3
def handle_number(i):
print(f"Hello friend {i}")
# Next number.
return i + 1
i = 0
# Use a while-True loop on one line.
while valid_number(i): i = handle_number(i)
Output
Hello friend 0
Hello friend 1
Hello friend 2
Hello friend 3
Version 1: This version of the code uses a for-loop. We loop over the strings, and sum their lengths.
Version 2: Here we use the while-loop. The logic is the same as version 1 of the code.
Result: The for-loop syntax faster that the while-loop syntax here. Prefer the for-loop on collections such as lists (when possible).
Python program that benchmarks loops
import time
names = ["San Jose", "Denver", "New York", "Phoenix"]
print(time.time())
# Version 1: for-loop.
i = 0
while i < 100000:
count = 0
# Loop.
for name in names:
count += len(name)
i = i + 1
print(time.time())
# Version 2: while-loop.
i = 0
while i < 100000:
count = 0
# Loop.
x = 0
while x < len(names):
count += len(names[x])
x = x + 1
i = i + 1
print(time.time())
Output
For-loop: 98 ms
While-loop: 219 ms