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

(vip2019) #1
Conditions (What If?) 79

bring an umbrella; otherwise, you don’t. In this chapter, we’ll learn
how to program the computer to make decisions based on whether
a condition is true or false.

if Statements


The if statement is an important programming tool. It allows us
to tell the computer whether to run a group of instructions, based
on a condition or set of conditions. With an if statement, we can
tell the computer to make a choice.
The syntax of the if statement—that is, the way we code an if
statement so the computer understands it—looks like this:

if condition:
indented statement(s)

The condition we’re testing in an if statement is usually a
Boolean expression, or a true/false test. A Boolean expression
evaluates to either True or False. When you use a Boolean expres-
sion with an if statement, you specify an action or set of actions
that you want performed if the expression is true. If the expression
is true, the program will run the indented statement(s), but if it’s
false, the program will skip them and continue with the rest of the
program at the next unindented line.
IfSpiral.py shows an example of an if statement in code:

IfSpiral.py

u answer = input("Do you want to see a spiral? y/n:")
v if answer == 'y':
w print("Working...")
import turtle
t = turtle.Pen()
t.width(2)
x for x in range(100):
y t.forward(x*2)
z t.left(89)
{ print("Okay, we're done!")

The first line of our IfSpiral.py program u asks the user
to enter y or n for whether they would like to see a spiral and
stores the user’s response in answer. At v, the if statement checks
to see if answer is equal to 'y'. Notice that the operator to test “is
Free download pdf