SPIKE™ Prime with Python

Guessing Game

Investigate using conditional statements with loops.

45 min
Intermed.
Years 7-9 or Key Stage 3

Questions to investigate

• Why would a programmer combine an if/elif/else conditional statement with a loop?

Prepare

• Ensure SPIKE Prime hubs are charged, especially if connecting through Bluetooth.
• Ensure students have built the Kiki, the Dog model, which was used in the Guess Which Color lesson.

Engage

(Group Discussion, 5 minutes)

Engage students in thinking about choosing from multiple options.

Prompt students to brainstorm how they make a choice when presented with several options. Ask students to image they are at a breakfast buffet with as many breakfast options as they can think of. How do they decide which things to eat? Ask students to select three items that they would choose to eat.

Let students share their choices. What influences help make their choices (mood, time, favorites, etc.)? Discuss how making a plate of food at the buffet is similar to creating a code that allows you to choose some items (add to the plate) while not choosing others (skip them in line).

Explore

(Small Groups, 20 minutes)

Students will explore programming the Kiki model to react to colors according to conditions set in a loop.

Direct students to open their saved program for the Guess Which Color lesson. Students should connect their hub. Consider having students run the program one time to remember how it works.

Using a loop with an if/elif/else statement
Ask students to think about how they could modify the program used in the Guess Which Color lesson to repeat the condition allowing the program to identify more than one color. Students should recognize that a while loop will allow the color sensor to continue to react to the color read according to the conditions set.

Ask students to update their flowchart from the Guess Which Color lesson or create a new flowchart to show how the program should work.

Allow students time to modify their program and try it. Remind students to watch the console for error messages. Suggest to students to save this as a new program so as not to lose the original program.

Sample program:

from hub import port
import runloop
import color_sensor
import color
from app import sound

async def main():
    #if the color sensor senses blue, it will play bird sound
    if color_sensor.color(port.A) == color.BLUE:
        await sound.play('Bird')
        print('Blue Detected')
    #if the color sensor senses green, it will play cat angry sound
    elif color_sensor.color(port.A) == color.GREEN:
        await sound.play('Cat Angry')
        print('Green Detected')
    #if the color sensor does not sense blue, it will play dog bark 1 sound
    else:
        await sound.play('Dog Bark 1')
        print('What happened?')

runloop.run(main())

Review the program with students. Discuss what changed as a result of having a loop in the program. Students should see that the loop allows the program to continue running after the first color is detected, which means the program will continue to react when a new color is presented.

Play a Guessing Game
Have students remove the other two colors of 2x4 bricks from their set. Have students rearrange their model to allow all five colors to fit. Students should rework their program to include a new condition for reading each color. Prompt students that more than one elif statement can be included. Working together have students program each brick to make a different sound.

Sample Program:

from hub import port
import runloop
import color_sensor
import color
from app import sound

async def main():
    #if the color sensor senses blue, it will play bird sound
    if color_sensor.color(port.A) == color.BLUE:
        await sound.play('Bird')
        print('Blue Detected')


    #if the color sensor senses green, it will play cat angry sound
    elif color_sensor.color(port.A) == color.GREEN:
        await sound.play('Cat Angry')
        print('Green Detected')


    #if the color sensor senses red, it will  play snoring sound
    elif color_sensor.color(port.A) == color.RED:
        await sound.play('Snoring')
        print('Red Detected')


    #if the color sensor senses magenta, it will play moo sound
    elif color_sensor.color(port.A) == color.MAGENTA:
        await sound.play('Moo')
        print('Magenta Detected')


    #if the color sensor sesnes yellow, it will play wobble sound
    elif color_sensor.color(port.A) == color.YELLOW:
        await sound.play('Wobble')
        print('Yellow Detected')


    #if the color sensor does not sense any of these colors, it will play dog bark 1 sound
    else:
        await sound.play('Dog Bark 1')
        print('What happened?')

runloop.run(main())

Each partner will take a turn being the game master and the other partner will play the guessing game. Without Partner 2 looking at the model, Partner 1 should play the program allowing the model to scan each color of the 2x4 bricks chosen. Partner 1 will get to decide which colors to scan. Partner 2 can listen to the sounds played in order to guess the color combination. Partner 2 can either write the color order down or use other pieces from the set to indicate the color order.

Have students check the guess at the end of the game and then switch partners.

Explain

(Whole Group, 5 minutes)

Discuss with students how the program worked.
Ask students questions like:
• How can a loop and conditional statement work together in one program?
• How is this program using more than one conditional statement?

Remind students that the while loop actually sets up a conditional statement as well. While that section of code is true, it will continue to repeat.
• How many conditions can you set in one program?
• When will the program end?

Elaborate

(Small Groups, 10 minutes)

Challenge students to try a new game where they are not detecting colors, but checking for bugs.

Show students each program and error message. Have students discuss what needs to change in each code to fix the bug or add the missing code. Consider making the changes as a class and ensuring the program runs correctly after each change.

Debug Activity 1:

from hub import port
import runloop
import color_sensor
import color

async def main():
    #if the color sensor senses blue, it will play bird sound
    if color_sensor.color(port.A) == color.BLUE:  
        await sound.play(‘Bird’)
        print('Blue Detected')
    #if the color sensor senses green, it will play dog bark 1 sound
    elif color_sensor.color(port.A) == color.GREEN:
        await ssound.play(‘Dog Bark 1’)
        print('Green Detected')
    #if the color sensor does not sense blue, it will play cat angry sound
    else
        await sound.play(‘Cat Angry’)
        print('What happened?')

runloop.run(main())

Traceback (most recent call last):
File "Project 2", line 17
SyntaxError: invalid syntax

Students should recognize that the error is in line 17 from the error message. The invalid syntax means that we have not formatted something in the code correctly. Looking at line 17, students should notice that the else statement should have a colon at the end (:) with the statement of what to do as the else written on the next line with an indent.

Debug Activity 2

from hub import port
import runloop
import color_sensor
import color
from app import sound

async def main():
    #if the color sensor senses blue, it will play bird sound
    if color_sensor.color(port.A) == color.BLUE:
    await sound.play('Bird')
    print('Blue Detected')
    #if the color sensor senses green, it will play cat angry sound
    elif color_sensor.color(port.A) == color.GREEN:
        await sound.play('Cat Angry')
        print('Green Detected')
    #if the color sensor does not sense blue, it will play dog bark 1 sound
    else:
        await sound.play('Dog Bark 1')
        print('What happened?')

runloop.run(main())


Traceback (most recent call last):
File "Color 2", line 8
SyntaxError: invalid syntax

Students should recognize that the error is in line 8 as indicated in the error message. The conditional statement created by the if is not reading the condition because the lines of code for the condition are not indented. To fix the program, students need to indent all the lines of code needed for the conditional (lines 8-9).

Ask students to indent line 8 and only line 8. Run the program again. Students will receive a new error message.

SyntaxError: invalid syntax
Traceback (most recent call last):
File "Color 2", line 12
SyntaxError: invalid syntax

Students should recognize that there is still an error in the code. By indenting line 8, we completed the conditional statement. The condition reads line 9 and then ends because line 9 is not indented.

Missing Code Activity

from hub import port
import runloop
import color_sensor
import color

async def main():
    #if the color sensor senses blue, it will play bird sound
    if color_sensor.color(port.A) == color.BLUE:
        await sound.play(‘Bird’)
        print('Blue Detected')
    #if the color sensor senses green, it will play dog bark 1    
    elif 
    #if the color sensor does not sense blue, it will play cat angry
    else

Discuss this program with students. Ask students what is missing to make this a complete program. Similar to debugging, you can run the program and receive an error message.

Traceback (most recent call last):
File "Project 2", line 12
SyntaxError: invalid syntax

In this case, the program sends an error for line 12 because the elif statement is not defined. Students need to add something that sets the new condition if the original condition is read as false.

Ask students to add a piece of code into the elif statement and try the program again. Students might have indicated a need to add to the else statement as well. If students run the new program, they will see a new error message to add a line of code to the else statement as well. Tell students that this error message did not show up before because the program will read the first error message and then stop. This means that additional messages are not initially called out.

Evaluate

(Group Exercise, 5 minutes)

Teacher Observation:
Discuss the program with students.
Ask students questions like:
• How can a loop and conditional statement work together in one program?
• What actions should you take when you receive an error message?
• How many elif statements can you include in a program?

Self-Assessment:
Have students answer the following in their journals:
• What did you learn today about adding multiple conditions in one program?
• What characteristics of a good teammate did I display today?
• Ask students to rate themselves on a scale of 1-3, on their time management today.
• Ask students to rate themselves on a scale of 1-3, on their materials (parts) management today.

Teacher Support

Students will:
• Write code that uses multiple condition statements using if/elif/else programming.
• Add a loop to code.
• Debug coding that has incorrect/missing syntax, missing code, or incorrect indention.

• SPIKE Prime sets ready for student use
• Devices with the SPIKE App installed
• Student journals

CSTA
2-CS-02 Design projects that combine hardware and software components to collect and exchange data.
2-AP-10 Use flowcharts and/or pseudocode to address complex problems as algorithms
2-AP-13 Decompose problems and subproblems into parts to facilitate the design, implementation, and review of programs.
2-AP-16 Incorporate existing code, media, and libraries into original programs, and give attribution.
2-AP-17 Systematically test and refine programs using a range of test cases.
2-AP-19 Document programs in order to make them easier to follow, test, and debug.