deutsch     english    français     Print

 

2.7 SELECTION

 

 

INTRODUCTION

 

What you do in your daily life often depends on certain conditions. So let's say you decide on how you will get to school today depending on the weather. You say: "In case it rains today, I'll take the tram, otherwise I'll ll ride my bike". Similar to this, flow of a program can also depend on certain conditions. Among the basic structures of any programming language are such program branches that depend on specific conditions. The instructions after if are only executed when the condition is true, otherwise the statements after else are executed.

PROGRAMMING CONCEPTS: Condition, program branching, selection, if-else structure

 

 

REVIEWING INPUTS

 

After you enter the side length in the dialog box, the square will only be drawn if it fits the window entirely.

We now examine the value of s. If s is less than 300 a square with the side length s is drawn, otherwise a message appears in the lower part of the Tigerjython window. In a programming language, this test is done using the if statement.
 


from gturtle import *

def square(sidelength):    
    repeat 4: 
        forward(sidelength) 
        right(90)
      
makeTurtle()
s = inputInt("Enter the side length")
if s < 300:
    square(s)    
else:  
    print("The side length is too big")
Highlight program code (Ctrl+C copy, Ctrl+V paste)

 

 

MEMO

 

The instructions after if are only executed if the condition is true, otherwise the statements after else are executed. You can also leave out the else block. Try it!

Please be aware of the colons after the if condition and after else, as well as a correct indentation of both program blocks.

 

 

MULTIPLE SELECTION

 

Now we would like to draw colored squares. You can enter the desired color by putting a number into the dialog box. In an if structure, the number is checked and then the appropriate fill color is set. We first test if the value is 1, then if it is 2 (with elif), and finally 3. For any other number entered, we use else to set the color to black.

With the command fill(10, 10) the closed area around the given point is filled with the specified fill color. Since after drawing the square, the turtle is back in the center of the window (0, 0), by using (10, 10) we select a point that is definitely inside of the square.
 
from gturtle import *

def square():    
    repeat 4: 
        forward(100) 
        right(90)
      
makeTurtle()
n = inputInt("Enter a number: 1:red 2:green 3:yellow")
if n == 1:
    setFillColor("red")
elif n == 2: 
    setFillColor("green") 
elif n == 3:
    setFillColor("yellow") 
else:
    setFillColor("black")        
    
square()
fill(10, 10)
Highlight program code (Ctrl+C copy, Ctrl+V paste)

 

 

MEMO

 

Several conditions can be checked consecutively. In a case where the condition at if is not fulfilled, the condition at elif is checked. elif is an abbreviation of else if. In a case where none of the elif conditions are fulfilled, any statements after else are executed.
It is very important to remember that in Python, a double equal sign is used in the test for equality. It may take time getting used to it, but it is necessary because the single equal sign is used for assignments.

Please be aware of the notations used for comparison operators: >, >= , < , <= , == , != .

With the command fill(x, y) you can fill closed figures with the fill color. However, the point (x, y) must be located inside of the figure.

 

 

COLOR CHOICE, BOOLEAN VARIABLES

 

In order to fill a figure afterwards using the fill() statement, its interior of the figure cannot already be occupied by another figure. You already know the startPath()/fillPath()combination with which you can correctly fill new figures that lay on top of existing figures. In this program you call askColor(), which brings up a nice dialog box with which you can choose the color of the star.

 

The star that you draw uses the function star(), which in addition to the size of the star also has a parameter filled whose value can be true or false and determines whether the star should be filled or not.

from gturtle import *

makeTurtle()

def star(size, filled):
    if filled:
        startPath()
    repeat 9:
        forward(size)
        left(175)
        forward(size)
        left(225)
    if filled:
        fillPath()

clear("black")
repeat 5:
    color = askColor("Color selection", "yellow")
    if color == None:
        break
    setPenColor(color) 
    setFillColor(color)
    setRandomPos(400, 400)
    back(100)
    star(100, True)
Highlight program code (Ctrl+C copy, Ctrl+V paste)

 

 

MEMO

 

The function askColor() has parameters for the text in the title bar and the color that is selected as the default value. When you click the OK button the function returns the selected color and when you click the cancel button instead, the function returns the special value none. You can test this value with an if statement and you can abort the repeat loop with break.

A variable or a parameter which can take the values true or false is called a boolean variable or a boolean parameter [more... The name comes from the mathematician George Boole, who invented the logical calculus]. You can directly test its value, for instance with if filled: It is thus not necessary (and not very elegant) to write if filled == True.

 

 

EXERCISES

 

1.

In the dialog box you ask the user how big the side length of a square should be. If it is less than 50, a red square is drawn with this side length. Otherwise a green square is drawn.

 


2.

Make the turtle draw a staircase with 10 steps using repeat 10. Make the first 5 levels blue and the rest of the levels red (Figure a).
(a)
(b)


Tell the turtle to draw a spiral, first using green, then red, and finally black (Figure b).