Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python For Kids (Level1-Level 2) - 6th Week

Uploaded by

tr.ryan.ict
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python For Kids (Level1-Level 2) - 6th Week

Uploaded by

tr.ryan.ict
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter 5. Conditions (What If?

)
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)

IfSpiral.py shows an example of an if statement in code:

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

Figure 5-2. If you answer y to the question in IfSpiral.py, you’ll see a spiral like this one.
Meet the Booleans
Boolean expressions, or conditional expressions, are important programming tools: the
computer’s ability to make decisions depends on its ability to evaluate Boolean
expressions to True or False.
We have to use the computer’s language to tell it the condition we’d like to test. The
syntax of a conditional expression in Python is this:
expression1 conditional_operator expression2

Comparison Operators
The comparison operators are shown in Table 5-1.
Table 5-1. Python Comparison Operators

Math symbol Python operator Meaning Example Result

< < Less than 1 < 2 True

> > Greater than 1 > 2 False

≤ <= Less than or equal to 1 <= 2 True

≥ >= Greater than or equal to 1 >= 2 False

= == Equal to 1 == 2 False

≠ != Not equal to 1 != 2 True

Figure 5-3. Testing conditional expressions in the Python shell


You’re Not Old Enough!
Let’s write a program that uses Boolean conditional expressions to see if you’re old
enough to drive a car. Type the following in a new window and save it as OldEnough.py.

OldEnough.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!")
if your_age < driving_age:
print("Sorry, you can drive in", driving_age - your_age, "years.")

Figure 5-4. I’m old enough to drive in the United States, but my five-year-old son isn’t.
Else Statements
Often we want our program to do one thing if a condition evaluates to True and something
else if the condition evaluates to False. This is so common, in fact, that we have a
shortcut, the else statement, that allows us to test if the condition is true without having to
perform another test to see if it’s false. The else statement can only be used after an if
statement, not by itself, so we sometimes refer to the two together as an if-else. The
syntax looks like this:
if condition:
indented statement(s)
else:
other indented statement(s)

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, "years.")
Polygons or Rosettes

PolygonOrRosette.py
import turtle
t = turtle.Pen()
# Ask the user for the number of sides or circles, default to 6
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
shape = turtle.textinput("Which shape do you want?",
"Enter 'p' for polygon or 'r' for rosette:")
for x in range(number):
if shape == 'r': # User selected rosette
t.circle(100)
else: # Default to polygon
t.forward (150)
t.left(360/number)

See Figure 5-5 for an example.

Figure 5-5. Our PolygonOrRosette.py program with user input of 7 sides and r for rosette
Even or Odd?
The if-else statement can test more than user input. We can use it to alternate shapes,
by using an if statement to test our loop variable each time it changes to see if it’s even
or odd. On every even pass through the loop — when our variable is equal to 0, 2, 4, and
so on — we can draw a rosette, and on every odd pass through the loop, we can draw a
polygon.

RosettesAndPolygons.py
# RosettesAndPolygons.py - a spiral of polygons AND rosettes!
import turtle
t = turtle.Pen()
# Ask the user for the number of sides, default to 4
sides = int(turtle.numinput("Number of sides",
"How many sides in your spiral?", 4))
# Our outer spiral loop for polygons and rosettes, from size 5 to 75
for m in range(5,75):
t.left(360/sides + 5)
t.width(m//25+1)
t.penup() # Don't draw lines on spiral
t.forward(m*4) # Move to next corner
t.pendown() # Get ready to draw
# Draw a little rosette at each EVEN corner of the spiral
if (m % 2 == 0):
for n in range(sides):
t.circle(m/3)
t.right(360/sides)
# OR, draw a little polygon at each ODD corner of the spiral
else:
for n in range(sides):
t.forward(m)
t.right(360/sides)
Figure 5-6. Two runs of our RosettesAndPolygons.py program with user inputs of 4 sides (top) and 5 sides (bottom)
Elif Statements

WhatsMyGrade.py
grade = eval(input("Enter your number grade (0-100): "))
if grade >= 90:
print("You got an A! :) ")
elif grade >= 80:
print("You got a B!")
elif grade >= 70:
print("You got a C.")
elif grade >= 60:
print("You got a D…")
else:
print("You got an F. :( ")
Complex Conditions: If, and, or, not
Table 5-2. Logical Operators

Logical operator Usage Result

and if(condition1 and condition2): True only if both condition1 and condition2 are True

or if(condition1 or condition2): True if either of condition1 or condition2 are True

not if not(condition): True only if the condition is False

WhatToWear.py
rainy = input("How's the weather? Is it raining? (y/n)").lower()
cold = input("Is it cold outside? (y/n)").lower()
if (rainy == 'y' and cold == 'y'): # Rainy and cold, yuck!
print("You'd better wear a raincoat.")
elif (rainy == 'y' and cold != 'y'): # Rainy, but warm
print("Carry an umbrella with you.")
elif (rainy != 'y' and cold == 'y'): # Dry, but cold
print("Put on a jacket, it's cold out!")
elif (rainy != 'y' and cold != 'y'): # Warm and sunny, yay!
print("Wear whatever you want, it's beautiful outside!")
Chapter 6. Random Fun and Games: Go
Ahead, Take a Chance!
A Guessing Game
GuessingGame.py
import random
the_number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
while guess != the_number:
if guess > the_number:
print(guess, "was too high. Try again.")
if guess < the_number:
print(guess, "was too low. Try again.")
guess = int(input("Guess again: "))
print(guess, "was the number! You win!")

Figure 6-1. Our GuessingGame.py program, asking the user to guess higher or lower for three random numbers

Colorful Random Spirals


The random module has other handy functions besides randint(). Let’s use them to help
us create an interesting visual: a screen full of spirals of random sizes and colors like the
one in Figure 6-2.
Figure 6-2. Spirals of random sizes and colors at random locations on the screen, from RandomSpirals.py

RandomSpirals.py
import random
import turtle
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple",
"white", "gray"]
for n in range(50):
# Generate spirals of random sizes/colors at random locations
t.pencolor(random.choice(colors)) # Pick a random color
size = random.randint(10,40) # Pick a random spiral size
# Generate a random (x,y) location on the screen
x = random.randrange(-turtle.window_width()//2,
turtle.window_width()//2)
y = random.randrange(-turtle.window_height()//2,
turtle.window_height()//2)
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(91)

You might also like