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

(vip2019) #1
Loops Are Fun (You Can Say That Again) 63

if one of them is greater or less than the other, or if they are equal
or not equal. Is x less than 7? Yes or no? True or False? Based on
the result, True or False, you can tell your program to run different
pieces of code.
The while loop shares some features with the for loop. First,
like the for loop, it repeats a set of statements over and over as
needed. Second, with both while loops and for loops, we tell Python
which statements to repeat by indenting them to the right with the
tab key.
Let’s try a program with a while loop to see it in action. Type
the following code (or download it from http://www.nostarch.com/
teachkids/), and run it:

SayOurNames.py

Ask the user for their name


u name = input("What is your name? ")


Keep printing names until we want to quit


v while name != "":


Print their name 100 times


w for x in range(100):


Print their name followed by a space, not a new line


x print(name, end = " ")
y print() # After the for loop, skip down to the next line


Ask for another name, or quit


z name = input("Type another name, or just hit [ENTER] to quit: ")
{ print("Thanks for playing!")


We begin the program by asking the user their name at u and
storing their answer in the variable name. We need a name to test as
the condition of our while loop, so we have to ask once before the loop
starts. Then, at v, we start our while loop, which will run as long as
the name the user enters is not an empty string (represented by two
double quotes with nothing between them: ""). The empty string is
what Python sees as the input when the user presses enter to quit.
At w, we start our for loop, which will print the name
100 times, and at x, we tell the print() statement to print a space
after the name each time. We’ll keep going back to w and checking
to see if x has reached 100, then printing at x until the name fills
a few lines of the screen. When our for loop has finished printing
the name 100 times, we print a blank line without a space y, mov-
ing the printout down to the next clear line. Then, it’s time to ask
for another name z.
Free download pdf