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

(vip2019) #1

86 Chapter 5


only makes the code shorter and easier to read, but it also helps
prevent coding errors in the two conditions. For example, if we
test your_age > driving_age in the first if statement and your_age <
driving_age in the second if statement, we might accidentally leave
out the case where your_age == driving_age. By using the if-else
statement pair, we can just test if your_age >= driving_age to see if
you’re old enough to drive and inform you if you are, and otherwise
go to the else statement and print how many years you must wait
to drive.
Here’s OldEnoughOrElse.py, a revised version of OldEnough.py
with an if-else instead of two if statements:

OldEnoughOrElse.py


driving_age = eval(input("What is the legal driving age where you live? "))
your_age = eval(input("How old are you? "))
if your_age >= driving_age:
print("You're old enough to drive!")
else:
print("Sorry, you can drive in", driving_age - your_age, "ye ars.")


The only difference between the two programs is that we
replaced the second if statement and condition with a shorter,
simpler else statement.

Polygons or Rosettes


As a visual example, we can ask the user to input whether they’d
like to draw a polygon (triangle, square, pentagon, and so on) or a
rosette with a certain number of sides or circles. Depending on the
user’s choice (p for polygon or r for rosette), we can draw exactly the
right shape.
Let’s type and run this example, PolygonOrRosette.py, which
has an if-else statement pair.
PolygonOrRosette.py

import turtle
t = turtle.Pen()
# Ask the user for the number of sides or circles, default to 6
u number = int(turtle.numinput("Number of sides or circles",
"How many sides or circles in your shape?", 6))
# Ask the user whether they want a polygon or rosette
v shape = turtle.textinput("Which shape do you want?",
"Enter 'p' for polygon or 'r' for rosette:")
Free download pdf