🔗Lesson 6: Compact code

Aim

The aim of this lesson is to learn how to use variables and functions in Python. While you've already learned how to use some functions, here you will be able to expand your capabilities with variables to create more readable, expandable and efficient code.

Variables

Challenge 1 : Control speed with variables

While getting into variables in Python may be scary at first, they are actually quite simple to use. You may recall from Lesson 7: Variables and Functionsthat they are a fundamental concept in programming that allow you to store and manage data throughout your program. They are containers that hold values, and you can refer to the values by using names.

A value in a variable can be both a number and a string. If you put the double quotes “ ” or single ‘ ‘ it will be identified as a string.

x = 50
y = "Hello"

You can use variables to simplify your code and make quick changes. Let's try rebuilding the variable blocks from Blocky in Python to control Misty's movement speed.

from mistyPy.Robot import Robot
import time

misty = Robot()
x = 40
speed = 60

misty.move_head(0, 0, 0, speed)
misty.move_arms(0, x, speed, speed)
time.sleep(1)
misty.move_arms(x, 0, speed, speed)
time.sleep(1)
misty.move_arms(0, x, speed, speed)
time.sleep(1)
misty.move_arms(x, 0, speed, speed)
time.sleep(1)

Remember to insert valid values in each comma space in a function. For example, a string where is expected an int is not accepted.

Challenge 2: Let's go global

Variables can be both defined inside a function (local variables) or made global. A global variable in programming is a variable that is accessible from any part of the program, unlike local variables which are accessible only within the scope they are declared as in the example above. Global variables are useful for storing data that needs to be accessed by multiple functions or parts of a program and can help you build larger and more complex event skill trees that use bump and touch sensors, face recognition, object detection, among others.

When you’re using the same variable in multiple functions you will need to define it as a global variable and define event handlers using the following syntax:

#first function that defines the conditions of an event
def eventname_1(data):
global variablename
    print(data)
    if statement
    variablename= True
    elif statement
    variablename= False
    

#second function that defines the outcomes of an event based on the conditions set in the first function
def eventname_2(data):
    print(data)
    if globalvariablename == True:
    #misty.display_image("e_Joy2.jpg", 1)
    else:
    #misty.display_image("e_Sadness.jpg", 1)

As you can see event handlers contain the code that defines what commands Misty should execute when a specific event is trigger. For example we can define our first event function as eventname_1 to handle a group of bump sensor events. The second event function can be defined as eventname_2, which will handle the responses for the events that are triggered in the first function. Both functions are linked together by a global variable called bumped. The next step is to determine how you want the global variable to handle reponses to a triggered event. You can do this by using conditions True or False for your global variable. This way you can create multiple responses based on whether one of the conditions is met. Now let's try setting up an event skill with global variables using the example below.

from mistyPy.Robot import Robot
from mistyPy.Events import Events
import time

misty = Robot()

misty.display_image("e_Contempt.jpg", 1)
misty.change_led(255, 255, 255)
time.sleep(1)

def bumped_1(data):
    global bumped #global variable
    print(data)
    if data["message"]["sensorId"] == 'bfr':
        misty.change_led(255, 255, 0)
        bumped = True #using global variable
        misty.transition_led(255, 255, 0, 255, 255, 255, "TransitOnce", 1000)
    elif data["message"]["sensorId"] == 'bfl':
        misty.change_led(0, 100, 255)
        bumped = False
        misty.transition_led(0, 100, 255, 255, 255, 255, "TransitOnce", 1000)
    else:
        misty.change_led(255, 255, 255)

def bumped_2(data):
    print(data)
    if bumped == True:
        misty.transition_led(255, 255, 255, 0, 255, 0, "TransitOnce", 1000)
        misty.display_image("e_Joy2.jpg", 1)
    else:
        misty.transition_led(255, 255, 255, 255, 0, 0, "TransitOnce", 1000)
        misty.display_image("e_Sadness.jpg", 1)

misty.register_event(event_name='bumped_1', event_type=Events.BumpSensor, callback_function=bumped_1, keep_alive=False)
misty.register_event(event_name='bumped_2', event_type=Events.BumpSensor, callback_function=bumped_2, keep_alive=True)

misty.keep_alive()

Functions

Challenge 3: Make a call to your functions

As you discovered throughout your programming journey, functions are fundamental to building any complex event skill both in Blockly and in Python. Since they usually require a lot of space you will eventually find yourself going back and forth between lines of code to find that perfect sequence that you really want to use again in another part of your program. To avoid let's build up a list of functions that you can call anywhere in your code.

In Python a function is defined using the def keyword followed by a custom name. For example you can define your function as 'Greeting', 'Driving', 'Dancing' and so on. If the function has no arguments you can just open and close your parenthesis “()”, otherwise if you have arguments you can insert their name in the parenthesis and separate them with a comma “ , ”.

To call a function in your code you just need to write in it's name followed by paranthesis as shown in the example below. There isn't a specific order for defining the functions. You can define them both before and after your working code.

from mistyPy.Robot import Robot
import time

misty = Robot()

#functions local library
def Misty_waves(): #creating a function
    for i in range(2):
        misty.move_arms(0, -40, 50, 50)
        time.sleep(1)
        misty.move_arms(-40, 0, 50, 50)
        
def Hello_world():
    misty.speak("Hello world!", 1)
    misty.move_head(0, 0, 0, 50)
    misty.move_arms(0, -40, 50, 50)
    misty.display_image("e_Joy.jpg", 1)
    misty.transition_led(255, 255, 255, 0, 255, 0, "TransitOnce", 1000)
# end of functions local library

#code
misty.drive_time(30, 0, 5000)
Hello_world()#calls your function
time.sleep(1)
Misty_waves() #calls your function
#end of the code

Challenge 4: Combine variables and functions

Now that you've covered all the basic of using variables and functions, let's combine them to create a slim and neat event skill that can call various functions when an event is triggered.

from mistyPy.Robot import Robot
from mistyPy.Events import Events
import time

misty = Robot()
misty.start_face_recognition()

def Misty_waves():
    for i in range(2):
        misty.move_arms(0, -40, 50, 50)
        time.sleep(1)
        misty.move_arms(-40, 0, 50, 50)

def reaction_to_Simone():
     #misty.play_audio("s_Awe.wav", 50)
     misty.transition_led(0, 255, 0, 255, 127, 0, "TransitOnce", 1000)

def reaction_to_Denis():
     #misty.play_audio("s_Awe2.wav", 50)
    misty.transition_led(255, 0, 0, 0, 0, 255, "TransitOnce", 1000)

def reaction_to_new_person(item):
    misty.speak("I'm Misty, nice to meet you" + item + "Why don't you come here to memorize your face?" + "So next time I can recognize you and we can play!", 1)
    misty.display_image("e_Joy.jpg", 1)
    misty.transition_led(70, 100, 160, 127, 255, 0, "TransitOnce", 1000)

def recognized(data):
    print(data)  
    global item #definition variable
    item = data["message"]["label"] #assigning a value to a variable
    misty.speak("Hi " + data["message"]["label"] + "Great to see you again", 1)
    if data["message"]["label"] == 'Simone':
        reaction_to_Simone() #calls your function
    elif data["message"]["PersonName"] == 'Denis':
        reaction_to_Denis()
    else :
        misty.change_led(0, 0, 0)
    Misty_waves() 
    reaction_to_new_person(item)
   
misty.register_event(event_name='face_recognition_event', event_type=Events.FaceRecognition, callback_function=recognized, keep_alive=False)

misty.keep_alive()

Up Next 👇

Last updated