Python Basics #14 — while Loop
Python provides two loop statements: while and for. Today we’ll cover the while loop.
A loop runs the same code repeatedly. A while loop has two parts: a test block and a body. The test runs first; if it’s True, the body runs. The loop keeps repeating until the test becomes False.
What happens when you run the simple while below?
# A while loop repeats until the test block evaluates to False.
i = 1
while True: # test block
print(i) # body💡 Today’s tip
If a program is stuck in an infinite loop, press
Ctrl + Cto terminate it.
Because the test is hardcoded to True, the loop never exits — it runs forever, printing 1.
Conversely, the code below never executes the body even once, because the first test is False:
i = 1
while False:
print(i)To print 1 to 10 with while:
i = 1
while i <= 10:
print(i)
i += 11
2
3
4
5
6
7
8
9
10Now let’s print each item of a list one at a time:
my_list = ['one', 'two', 'three', 'four', 'five']
index = 0
last_index = 4
while index <= last_index:
print(my_list[index])
index += 1one
two
three
four
fiveIn real programs, data like my_list usually comes from a database or an external source rather than being hardcoded. So you often don’t know the item count up front. The code above has a problem: if the number of list items grows or shrinks, you have to update the hardcoded last_index. The standard fix is to compute the bound from len:
my_list = ['one', 'two', 'three', 'four', 'five']
index = 0
last_index = len(my_list) - 1
while index <= last_index:
print(my_list[index])
index += 1Sometimes you intentionally want an infinite loop — a condition that’s always True. Here’s a program that prints the current time once per second for as long as it runs:
from datetime import datetime
import time
while True:
print(datetime.now())
time.sleep(1)2023-03-18 15:12:12.176344
2023-03-18 15:12:13.188636
2023-03-18 15:12:14.201926
2023-03-18 15:12:15.216212
2023-03-18 15:12:16.216538
2023-03-18 15:12:17.228829
2023-03-18 15:12:18.240128
2023-03-18 15:12:19.254411
2023-03-18 15:12:20.260723
...Now an infinite-loop program that asks the user for a password. Code after the while block doesn’t run until the correct password is entered. When it is, break exits the loop and the next statement runs.
password = '1234'
balance = 10000
while True:
user_input = input('[Prompt] Enter your password: ')
if user_input != password:
print('Wrong password.\\n')
else:
print('Login successful.')
break
print('Your account balance is {}.'.format(balance))[Prompt] Enter your password: 123
[Prompt] Enter your password: 111
Wrong password.
[Prompt] Enter your password: 123
Wrong password.
[Prompt] Enter your password: 1234
Login successful.
Your account balance is 10000.That wraps up the while loop. In the next lesson we’ll cover the for loop.