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

(vip2019) #1

80 Chapter 5


equal to” uses two equal signs together, ==, to distinguish it from
the assignment operator, which is a single equal sign like at u.
The == operator checks to see if answer and 'y' are equal. If they
are, the condition in our if statement is true. We use a pair of
single quotation marks (') around a letter or other character when
we’re testing a variable to see if it contains a single character
entered by the user.
If our condition at v is true, we print Working... on the screen
at w, then draw a spiral on the screen. Notice that the print state-
ment at w and the statements that draw the spiral all the way
down to z are indented. These indented statements will be exe-
cuted only if the condition at v is true. Otherwise, the program
will skip all the way to { and just print Okay, we're done!.
The statements after our for loop at x are indented farther
(y and z). This is because they belong to the for statement. Just
as we added a loop inside another loop in Chapter 4 by indenting
the nested loop, we can put a loop inside an if statement by indent-
ing the whole loop.
Once the spiral is complete, our program picks back up at { and
tells the user we’re done. This is also the line our program jumps
to if the user typed n or anything other than y at u. Remember, the
whole if block from w through z is skipped if the condition at v is
False.
Type IfSpiral.py in a new IDLE window or download it from
http://www.nostarch.com/teachkids/, and run it a few times, test-
ing different answers. If you enter the letter y when prompted,
you’ll see a spiral like the one in Figure 5-2.
Free download pdf