Chapter 2 – Sensor Fusion and Coding Structures
2.3 – Selection Code Structures
So far we’ve learned about conditionals using basic if statements and comparators and how they can be used to create a remote control.
Let’s do a quick review:
What is logic?
In programming, logic refers to the flow of code that is used to execute a program. It can be a combination of various types of conditions that are created to fit a scenario.
Think about a traffic light. If you were to program a traffic light, you would have to write different code for the three different lights, based on what they mean. Can you think of any other examples?
If statements
An if statement is a conditional statement that is written to test a condition in a program, and if the specified condition is met, then only is the code inside the if statement run.
If-else statements
Let’s say that you had multiple conditions, however, you also wanted the program to do something if none of the conditions were met. In such a case, you can use if-else statements.
Recall that “Else” has no condition! This is because “else” is the last option when using if-else statements. When a computer reaches the “else” option after checking all the other conditions, then the else condition is automatically true and will run its statements.
One way to use “else” would be when something needs to happen when a condition is false. When the “if” condition is false and nothing needs to happen, don’t use an “else”.
An example in pseudocode has been provided below:
get the current fruit
if the current fruit == "apple":
print "apple"
if the current fruit == "banana":
print "banana"
if the current fruit == "orange":
print "orange"
else:
print "not an apple, banana, or orange"
Multiple if statements
Inside our code, we can have multiple if statements. Typically, each if statement has its own condition, and so if you are testing for multiple conditions, you can create an if statement for each condition.
Implementing logic using if statements
When implementing logic using if statements, a general rule of thumb is too look for all the conditions in your logic. Ask youself, at which points are you comparing items in your code? Are there any points, where you are checking if a certain variable of value is True or False? All of these logic portions can be written using if statements.
Activity
Using what we’ve learned today and our knowledge on if statements, let’s create a program, that changes Zumi’s expressions based on the key that is pressed. A started code with some pseudocode has been provided below.
from zumi.zumi import Zumi
import time
zumi = Zumi()
from zumi.util.screen import Screen
screen = Screen()
if key_pressed == "a":
zumi should be angry
if key_pressed == "s":
zumi should be sad
if key_pressed == "w":
zumi should say hello
else:
zumi should be confused
Demo Video
Questions