The while loop
The while loop in python acts a bit differently than the for. While the for operates
over the items of an Iterable, the while loop acts on a boolean condition.
To be more precise, a while loop may be used when the exact number of iterations is unknown. known.
For example, looping until the user gives a valid input:
# uci_bootcamp_2021/examples/while_loops.py
... # code omitted for brevity (see source file in repository)
# initialize valid to False.
valid = False
result = -1
# loop while the user hasn't given us a suitable value.
while not valid:
# get the user's untrusted input.
untrusted_input = input(prompt)
# check if the input is numeric.
if untrusted_input.isnumeric():
# if its numeric, we can safely interpret it as an integer
result = int(untrusted_input)
# then we can check the bounds
valid = valid_minimum <= result <= valid_maximum
if not valid:
print("invalid input, please try again!")
... # code omitted for brevity (see source file in repository)
This example has a decent bit of complexity so let's unpack it a bit.
# loop while the user hasn't given us a suitable value.
while not valid:
Here we define our while loop. We specifically loop while valid is False.
- We don't know how many times the user will give us invalid input; only that the input will be eventually valid given enough iterations.
# get the user's untrusted input.
untrusted_input = input(prompt)
Here we actually prompt the user for an input, using the built-in input function.
input()always returns astring. To accept an integer, the result ofinputneeds to be cast or otherwise parsed.
Speaking of converting the input to a string, that is the next step!
Before we can safetly cast the string to an integer, we should first check that the contents of the string is actually numerical.
str.isnumeric returns a boolean, True if the string is nothing but numerical digits.
if untrusted_input.isnumeric():
# if its numeric, we can safely interpret it as an integer
result = int(untrusted_input)
Now that the result is an integer, we can do the bounds check.
# then we can check the bounds
valid = valid_minimum <= result <= valid_maximum
Conversely, if the numerical or bounds checks fail, we should tell the user off!
if not valid:
print("invalid input, please try again!")
Note that the level of indentation decreased. the
if not validis at the same level of indentation as theif untrusted_input.isnumeric()!Python has significant whitespace!