Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

62 Chapter 4


run our program, but we need to give them the ability to play
again without having to reload and run the program every time.
Can you imagine if you had to restart an Xbox or PlayStation
every time you wanted to play a game again, or if you always had
to play a game exactly 10 times before moving on to a different
one? That might make it less fun.
One way we solve the game loop problem is by using another
type of loop, the while loop. Instead of iterating over a predefined
list of values, as the for loop does, a while loop can check for a
condition or situation and decide whether to loop again or end the
loop. The syntax of the while statement looks like this:

while condition:
indented statement(s)

The condition is usually a Boolean expression, or true/false test.
One everyday example of a while loop is eating and drinking. While
you are hungry, you eat. When the answer to the question “Am I
hungry?” is no longer yes, that means the condition “I am hungry”
is no longer true, and you stop eating. While you are thirsty, you
take another drink of water. When you stop feeling thirsty, you quit
drinking. Hunger and thirst are conditions, and when those condi-
tions become false, you exit the eating and drinking “loops.” A while
loop continues repeating the statements in the loop (the indented
statements) as long as the condition is true.
The true/false conditions in
while loops often involve comparing
values. We might say, “Is the value
of x bigger than 10? As long as it is,
run this code. When x isn’t bigger
than 10 anymore, stop running the
code.” In other words, we run the
code while the condition x > 10
evaluates to True. The greater-
than symbol (>) is a comparison
operator, a different kind of
operator from arithmetic opera-
tors like + (plus) and – (minus).
Comparison operators—such
as > (greater than), < (less than),
== (equal to), or != (not equal to)—
let you compare two values to see
Free download pdf