Previous: [Chapter 2](Chapter 2.ipynb)[Learning Computing with Robots](Learning Computing with Robots.ipynb)Next: [Chapter 4](Chapter 4.ipynb)

3: Building Robot Brains

Home Simpson’s Brain Photo courtesy of [The Simpson’s Trivia](http://www.simpsonstrivia.com)

What a splendid head, yet no brain.

Aesop (620 BC-560 BC)

If you think of your robot as a creature that acts in the world, then by programming it, you are essentially building the creature's brain. The power of computers lies in the fact that the same computer or the robot can be supplied a different program or brain to make it behave like a different creature. For example, a program like Firefox or Explorer makes your computer behave like a web browser. But switching to your Media Player, the computer behaves as a DVD or a CD player. Similarly, your robot will behave differently depending upon the instructions in the program that you have requested to run on it. In this chapter we will learn about the structure of Python programs and how you can organize different robot behaviors as programs.

The world of robots and computers, as you have seen so far, is intricately connected. You have been using a computer to connect to your robot and then controlling it by giving it commands. Most of the commands you have used so far come from the Myro library which is specially written for easily controlling robots. The programming language we are using to do the robot programming is Python. Python is a general purpose programming language. By that we mean that one can use Python to write software to control the computer or another device like a robot through that computer. Thus, by learning to write robot programs you are also learning how to program computers. Our journey into the world of robots is therefore intricately tied up with the world of computers and computing. We will continue to interweave concepts related to robots and computers throughout this journey. In this chapter, we will learn more about robot and computer programs and their structure.

Basic Structure of a Robot Brain

def main():
   <do something>
   <do something else>
   ...


This is essentially the same as defining a new function. In fact, here, we are adopting a convention that all our programs that represent robot brains will be called main. In general, the structure of your robot programs will be as shown below (we have provided line numbers so we can refer to them):

Line 1: from myro import *
Line 2: init()

Line 3: <any other imports>
Line 4: <function definitions>
Line 5: def main():
Line 6:     <do something>
Line 7:     <do something>
Line 8:     ...

Line 9: main()

Every robot brain program will begin with the first two lines (Line 1 and Line 2). These, as you have already seen, import the Myro library and establish a connection with the robot. In case you are using any other libraries, you will then import them (this is shown in Line 3). This is followed by the definitions of functions (Line 4), and then the definition of the function, main. Finally, the last line (Line 9) is an invocation of the function main. This is placed so that when you load this program into the Python Shell the program will start executing. In order to illustrate this, let us write a robot program that makes it do a short dance using the yoyo and wiggle movements defined in the last chapter.

In [1]:
# Purpose: A simple dance routine

# First import myro and connect to the robot

from Myro import *
initialize()
 
# Define the new functions...

def yoyo(speed, waitTime):
    forward(speed, waitTime)
    backward(speed, waitTime)

def wiggle(speed, waitTime):
    motors(-speed, speed)
    wait(waitTime)
    motors(speed, -speed)
    wait(waitTime)
    stop()

# The main dance program
def main():
    print ("Running the dance routine...")
    yoyo(0.5, 0.5)
    wiggle(0.5, 0.5)
    yoyo(1, 1)
    wiggle(1, 1)
    print ("...Done")
You are using:
   Simulated Fluke, version 1.0.0
   Simulated Scribbler 2, version 1.0.0
Hello, my name is 'Scribby'!

We have used a new Python command in the definition of the main function: the print function. This command will print out the text enclosed in double quotes (") when you run the program. This program is not much different from the dance function defined in the previous chapter except we are using a spin motion to wiggle. However, instead of naming the function dance we are calling it main. As we mentioned earlier, this is just a naming convention that we are adopting that makes it easy to identify the main program in a program file.

In order to run this program on the robot, you can enter the in the program and run the main() function.

In [2]:
main()
Running the dance routine...
...Done

Or alternativey, you can save it as a file (using %%file dance.py) and enter import the module explicitly.

In [3]:
%%file dance.py
# Purpose: A simple dance routine

# First import myro and connect to the robot

from Myro import *
initialize()
 
# Define the new functions...

def yoyo(speed, waitTime):
    forward(speed, waitTime)
    backward(speed, waitTime)

def wiggle(speed, waitTime):
    motors(-speed, speed)
    wait(waitTime)
    motors(speed, -speed)
    wait(waitTime)
    stop()

# The main dance program
def main():
    print ("Running the dance routine...")
    yoyo(0.5, 0.5)
    wiggle(0.5, 0.5)
yoyo(1, 1)
wiggle(1, 1)
print ("...Done")

main()
Writing "dance.py"... done!
In [4]:
from dance import *
main()
You are using:
   Simulated Fluke, version 1.0.0
   Simulated Scribbler 2, version 1.0.0
Hello, my name is 'Scribby'!
...Done
Running the dance routine...
Running the dance routine...

When you run the program you will notice that the robot carries out the dance routine specified in the main program. Also notice the two messages printed in the IDLE window. These are the results of the print command. print is a very useful command in Python and can be used to output essentially anything you ask it to. Another option is to use speak:

In [9]:
speak("Running the dance routine")
Running the dance routine

speak is a Myro command that enables speech output from your computer. Go ahead and change the other print command also to the speak command and try your program. Once done, enter some other speak commands. For example:

In [11]:
speak("Dude! Pardon me, would you have any Grey Poupon?")
Dude! Pardon me, would you have any Grey Poupon?

The speech facility is built into most computers these days. Later we will see how you can find out what other voices are available and also how to change to them.

Speaking Pythonese

We have launched you into the world of computers and robots without really giving you a formal introduction to the Python language. In this section, we provide more details about the language. What you know about Python so far is that it is needed to control the robot. The robot commands you type are integrated into Python by way of the Myro library. Python comes with several other useful libraries or modules that we will try and learn in this course. If you need to access the commands provided by a library, all you have to do is import them.

The libraries themselves are largely made up of sets of functions (they can contain other entities but more on that later). Functions provide the basic building blocks for any program. Typically, a programming language (and Python is no exception) includes a set of pre-defined functions and a mechanism for defining additional functions. In the case of Python, it is the def construct. You have already seen several examples of function definitions and indeed have written some of your own by now. In the def construct, when defining a new function, you have to give the new function a name. Names are a critical component of programming and Python has rules about what forms a name.

What's in a name?

A name in Python must begin with either an alphabetic letter (a-z or A-Z) or the underscore (i.e. _) and can be followed by any sequence of letters, digits, or underscore letters. For example,

iRobot
myRobot
jitterBug
jitterBug2
my2cents
my_2_cents

are all examples of valid Python names. Additionally, another important part of the syntax of names is that Python is case sensitive. That is the names myRobot and MyRobot and myrobot are distinct names as far as Python is concerned. Once you name something a particular way, you have to consistently use that exact case and spelling from then on. Well, so much about the syntax of names, the bigger question you may be asking is what kinds of things can (or should) be named?

So far, you have seen that names can be used to represent functions. That is, what a robot does each time you use a function name (like yoyo) is specified in the definition of that function. Thus, by giving functions a name you have a way of defining new functions. Names can also be used to represent other things in a program. For instance, you may want to represent a quantity, like speed or time by a name. In fact, you did so in defining the function yoyo which is also shown below:

In [15]:
def yoyo(speed, waitTime):
    forward(speed, waitTime)
    backward(speed, waitTime)

Functions can take parameters that help customize what they do. In the above example, you can issue the following two commands:

In [16]:
yoyo(0.8, 2.5)
In [17]:
yoyo(0.3, 1.5)

The first command is asking to perform the yoyo behavior at speed $0.8$ for $2.5$ seconds where as the second one is specifying $0.3$ and $1.5$ for speed and time, respectively. Thus, by parameterizing the function with those two values, you are able to produce similar but varying outcomes. This idea is similar to the idea of mathematical functions: $\sin(x)$ for example, computes the sine of whatever value you supply for $x$. However, there has to be a way of defining the function in the first place that makes it independent of specific parameter values. That is where names come in. In the definition of the function yoyo you have named two parameters (the order you list them is important): speed and waitTime. Then you have used those names to specify the behavior that makes up that function. That is the commands forward, and backward use the names speed and waitTime to specify whatever the speed and wait times are included in the function invocation. Thus, the names speed and waitTime represent or designate specific values in this Python program.

Names in Python can represent functions as well as values. What names you use is entirely up to you. It is a good idea to pick names that are easy to read, type, and also appropriately designate the entity they represent. What name you pick to designate a function or value in your program is very important, for you. For example, it would make sense if you named a function turnRight so that when invoked, the robot turned right. It would not make any sense if the robot actually turned left instead, or worse yet, did the equivalent of the yoyo dance. But maintaining this kind of semantic consistency is entirely up to you.

Values

In the last section we saw that names can designate functions as well as values. While the importance of naming functions may be obvious to you by now, designating values by names is an even more important feature of programming. By naming values, we can create names that represent specific values, like the speed of a robot, or the average high temperature in the month of December on top of the Materhorn in Switzerland, or the current value of the Dow Jones Stock Index, or the name of your robot, etc. Names that designate values are also called variables. Python provides a simple mechanism for designating values with names:

In [18]:
speed = 0.75
aveHighTemp = 37
DowIndex = 12548.30
myFavoriteRobot = "C3PO"

Values can be numbers or strings (anything enclosed in double-quotes, "). The above are examples of assignment statements in Python. The exact syntax of an assignment statement is given below:

<variable name> = <expression>

You should read the above statement as: Let the variable named by <variable name> be assigned the value that is the result of calculating the expression <expression>. So what is an <expression>? Here are some examples:

In [19]:
5
Out[19]:
5
In [20]:
5 + 3
Out[20]:
8
In [21]:
3 * 4
Out[21]:
12
In [22]:
3.2 + 4.7
Out[22]:
7.9
In [23]:
10 / 2
Out[23]:
5

These Python snippets are called expressions. The simplest expression you can type is a number (as shown above). A number evaluates to itself. That is, a 5 is a 5, as it should be! And 5 + 3 is 8. As you can see when you enter an expression, Python evaluates it and then outputs the result. Also, addition (+), subtraction (-), multiplication (*), and division (/) can be used on numbers to form expressions that involve numbers.

You may have also noticed that numbers can be written as whole numbers ($3$, $5$, $10$, $1655673$, etc) or with decimal points ($3.2$, $0.5$, etc) in them. Python (and most computer languages) distinguishes between them. Whole numbers are called integers and those with decimal points in them are called floating point numbers. While the arithmetic operations are defined on both kinds of numbers, there are some differences you should be aware of. Look at the examples below:

In [24]:
10.0 / 3.0
Out[24]:
3.33333333333333
In [2]:
10 / 3
Out[2]:
3.33333333333333
In [33]:
10 / 3.0
Out[33]:
3.33333333333333
In [31]:
10 // 3
Out[31]:
3
In [26]:
1 // 2
Out[26]:
0
In [29]:
1 / 2
Out[29]:
0.5

When you divide a floating point number by another floating point number, you get a floating point result. And when you divide an integer by another integer, you can also get a floating point number. Thus, in the examples above, you get the result 3.3333333333333335 when you divide 10.0 by 3.0, as well as when divide 10 by 3 or 10 by 3.0.

However, there is another mathematical operation: integer division (or floor division) that results in an integer quotient. The expression 10 // 3 results in 3 because the fractional component is truncated. Thus, the result of dividing 1 by 2 (1//2) is zero (0).

There are two division operators / and //. Most of the time we'll use regular division that results in a floating point number, but sometimes integer division is useful. More on numbers later, before we get back to robots, let us quickly introduce you to strings.

Computers came to be called so because they excelled in doing calculations. However, these days, computers are capable of manipulating any kind of entity: text, images, sounds, etc. Text is made of letters or characters and strings are simply sequences of characters. Python requires that strings be written enclosed in quotes: which could be single ('I am a string'), double ("Me too!"), or even triple quotes ('''I'm a string as well!'''). Treating a string as a value is a powerful feature of Python. Python also provides some operations on strings using which you can write some useful string expressions. Here are some examples:

In [34]:
mySchool = "Bryn Mawr College"
yourSchool = "Georgia Institute of Technology"
print(mySchool)
Bryn Mawr College
In [35]:
print(yourSchool)
Georgia Institute of Technology
In [36]:
print(mySchool, yourSchool)
Bryn Mawr College Georgia Institute of Technology
In [37]:
yourSchool+mySchool
Out[37]:
Georgia Institute of TechnologyBryn Mawr College
In [41]:
print(yourSchool+mySchool)
Georgia Institute of TechnologyBryn Mawr College

Pay special attention to the last two examples. The operation + is defined on strings and it results in concatenating the two strings. The print command is followed by zero or more Python expressions, separated by commas. print evaluates all the expressions and prints out the results on the screen. As you have also seen before, this is a convenient way to print out results or messages from your program.

A Calculating Program

Ok, set your robot aside for just a few more minutes. You have now also learned enough Python to write programs that perform simple, yet interesting, calculations. Here is a simple problem:

On January 1, 2008 the population of the world was estimated at approximately 6.650 billion people. It is predicted that at current rates of population growth, we will have over 9 billion people by the year 2050. A gross estimate of population growth puts the annual increase at +1.14% (it has been as high as +2.2% in the past). Given this data, can you estimate by how much the world’s population will increase in this year (2008)? Also, by how much will it increase each day?

In order to answer the questions, all you have to do is compute $1.14\%$ of $6.650$ billion to get the increase in population this year. If you divide that number by $366$ (the number of days in 2008) you will get average daily increase. You can just use a calculator to do these simple calculations. You can also use Python to do this in two ways. You can use it as a calculator as shown below:

In [42]:
6650000000*1.14/100.0
Out[42]:
75810000
In [43]:
207131.1475409836
Out[43]:
207131.147540984

That is, in this year there will be an increase of $75.81$ million in the world’s population which implies an average daily increase of over $207$ thousand people). So now you know the answer!

Also, let us try and write a program to do the above calculations. A program to do the calculation is obviously going to be a bit of overkill. Why do all the extra work when we already know the answer? Small steps are needed to get to higher places. So let’s indulge and see how you would write a Python program to do this. Below, we give you one version:

In [1]:
#File: worldPop.py
# Purpose: 
#     Estimate the world population growth in a year and
#     also per day.
#     Given that on January 1, 2008 the world's population was
#     estimated at 6,650,000,000 and the estimated growth is
#     at the rate of +1.14%
def main():
    population = 6650000000
    growthRate = 1.14/100.0
    growthInOneYear = population * growthRate
    growthInADay = growthInOneYear / 365
    print ("World population on January 1, 2008 is", population)
    print ("By Jan. 1, 2009, it will grow by", growthInOneYear)
    print ("An average daily increase of", growthInADay)
main()
World population on January 1, 2008 is 6650000000
By Jan. 1, 2009, it will grow by 75810000.0
An average daily increase of 207698.630137
The Energy Problem
The root cause of world energy problems is growing world population and energy consumption per capita. How many people can the earth support? Most experts estimate the limit for long-term sustainability to be between 4 and 16 billion.
From: Science, Policy & The Pursuit of Sustainability, Edited by Bent, Orr,and Baker. Illus. by Shetter. Island Press, 2002.

The program follows the same structure and conventions we discussed above. In this program, we are not using any libraries (we do not need any). We have defined variables with names population, and growthRate to designate the values given in the problem description. We also defined the variables grothInOneYear and growthInADay and use them to designate the results of the calculations. First, in the main program we assign the values given, followed by performing the calculation. Finally, we use the print commands to print out the result of the computations.

You are now well on your way to also learning the basic techniques in computing! In this simple program, we did not import anything, nor did we feel the need to define any functions. But this was a trivial program. However, it should serve to convince you that writing programs to do computation is essentially the same as controlling a robot.

Using Input

The program we wrote above uses specific values of the world's population and rate of growth. Thus, this program solves only one specific problem for the given values. What if we wanted to calculate the results for a different growth rate? or even a different population? What if we wanted to try out the program for varying quantities of both? Such a program would be much more useful and could be used over and over again. Notice that the program begins by assigning specific values to the two variables:

In [3]:
population = 6650000000
growthRate = 1.14/100.0

One thing you could do is simply modify those two lines to reflect the different values. However, typical programs are much more complicated than this one and it may require a number of different values for solving a problem. When programs get larger, it is not a good idea to modify them for every specific problem instance but it is desirable to make them more useful for all problem instances. One way you can achieve this is by using the input facilities of Python. All computer programs typically take some input, do some computation (or something), and then produce some output. Python has a simple input command that can be used to rewrite the program above as follows:

In [1]:
# Purpose: 
#     Estimate the world population
#     growth in a year and
#     also per day.
#     Given that on January 1, 2008 
#     the world's population was
#     estimated at 6,650,000,000 and the estimated growth is
#     at the rate of +1.14%

def main():
    # print out the preamble
    print ("This program computes population growth figures.")
    # Input the values
    population = float(input("Enter current world population: "))
    growthRate = float(input("Enter the growth rate: "))/100.0
    # Compute the results
    growthInOneYear = population * growthRate
    growthInADay = growthInOneYear / 365
    # output results
    print ("World population today is", population)
    print ("In one year, it will grow by", growthInOneYear)
    print ("An average daily increase of", growthInADay)
    
main()
This program computes population growth figures.
Enter current world population: 6650000000
Enter the growth rate: 1.14
World population today is 6650000000.0
In one year, it will grow by 75810000.0
An average daily increase of 207698.630137

Read the program above carefully. Notice that we have added additional comments as well as print statements. This improves the overall readability as well as the interaction of this program. Notice the use of the input statements above. The basic syntax of input is shown below:

<variable name> = float(input(<some prompt string>))

That is, the float(input(...)) is a function (actually, two functions) whose parameter is a string and the value it returns is the value of the expression that will be entered by the user. When executed, the computer will ask the user to enter a something.

The user can enter something in response to the prompt and then hit the OK button (or press ENTER). Whatever one enters is first treated as a string and then converted to a floating point value. That value is then assigned to the variable . You can see that there are two functions being used here: input(...) which prompts the user for input. It returns a string containing whatever the user enters (e.g. '6650000000'); and float(...) which converts the input string to a number (the floating point number 6650000000). The statement above uses the same syntax as the assignment statement. With this modification, we now have a more general program which can be run again and again. Below, we show two sample runs:

In [6]:
main()
This program computes population growth figures.
Enter current world population: 6650000000
Enter the growth rate: 1.14
World population today is 6650000000.0
In one year, it will grow by 75810000.0
An average daily increase of 207698.630137
In [5]:
main()
This program computes population growth figures.
Enter current world population: 6725810000
Enter the growth rate: 2.2
World population today is 6725810000.0
In one year, it will grow by 147967820.0
An average daily increase of 405391.287671

Notice how you can re-run the program by just typing the name of the main() function. There are other ways of obtaining input in Python. We will see those a little later.

Robot Brains

Writing programs to control your robot is therefore no different from writing a program to perform a computation. They both follow the same basic structure. The only difference is that all robot programs you will write will make use of the Myro library. There will be several robot programs that will require you to obtain input from the user (see exercises below). You can then make use of the input function as described above.

One characteristic that will distinguish robot programs from those that just do computations is in the amount of time it will take to run a program. Typically, a program that only performs some computation will terminate as soon as the computation is completed. However, it will be the case that most of the time your robot program will require the robot to perform some task over and over again. Here then, is an interesting question to ask:

Question: How much time would it take for a vacuuming robot to vacuum a $16$ft x $12$ft room?

Seemingly trivial question but if you think about it a little more, you may reveal some deeper issues. If the room does not have any obstacles in it (i.e. an empty room), the robot may plan to vacuum the room by starting from one corner and then going along the entire length of the long wall, then turning around slightly away from the wall, and traveling to the other end. In this manner, it will ultimately reach the other side of the room in a systematic way and then it could stop when it reaches the last corner. This is similar to the way one would mow a flat oblong lawn, or even harvest a field of crop, or re-ice an ice hockey rink using a Zamboni machine. To answer the question posed above all you have to do is calculate the total distance travelled and the average speed of the vacuum robot and use the two to compute the estimated time it would take. However, what if the room has furniture and other objects in it?

You might try and modify the approach for vacuuming outlined above but then there would be no guarantee that the floor would be completely vacuumed. You might be tempted to redesign the vacuuming strategy to allow for random movements and then estimate (based on average speed of the robot) that after some generous amount of time, you can be assured that the room would be completely cleaned. It is well known (and we will see this more formally in a later chapter) that random movements over a long period of time do end up providing uniform and almost complete coverage. Inherently this also implies that the same spot may very well end up being vacuumed several times (which is not necessarily a bad thing!). This is similar to the thinking that a herd of sheep, if left grazing on a hill, will result, after a period of time, in a nearly uniform grass height (think of the beautiful hills in Wales).

Question: How does a vacuuming robot know that it is done cleaning the room?

Most robots are programmed to either detect certain terminating situations or are run based on time. For example, run around for 60 minutes and then stop. Detecting situations is a little difficult and we will return to that in the next chapter.

So far, you have programmed very simple robot behaviors. Each behavior which is defined by a function, when invoked, makes the robot do something for a fixed amount of time. For example, the yoyo behavior from the last chapter when invoked as:

In [20]:
yoyo(0.5, 1)

would cause the robot to do something for about 2 seconds (1 second to go forward and then 1 second to move backward). In general, the time spent carrying out the yoyo behavior will depend upon the value of the second parameter supplied to the function. Thus if the invocation was:

In [21]:
yoyo(0.5, 5.5)

the robot would move for a total of $11$ seconds. Similarly, the dance behavior defined in the previous chapter will last a total of six seconds. Thus, the total behavior of a robot is directly dependent upon the time it would take to execute all the commands that make up the behavior. Knowing how long a behavior will take can help in pre-programming the total amount of time the overall behavior could last. For example, if you wanted the robot to perform the dance moves for 60 seconds, you can repeat the dance behavior ten times. You can do this by simply issuing the dance command 10 times. But that gets tedious for us to have to repeat the same commands so many times. Computers are designed to do repetitious tasks. In fact, repetition is one of the key concepts in computing and all programming languages, including Python, provide simple ways to specify repetitions of all kinds.

Doing Repetition in Python

If you wanted to repeat the dance behavior $10$ times, all you have to do is:

In [ ]:
for i in range(10):
    dance()

This is a new statement in Python: the for-statement. It is also called a loop statement or simply a loop. It is a way of repeating something a fixed number of times. The basic syntax of a for-loop in Python is:

for <variable> in <sequence>:
   <do something>
   <do something else>
   ...

The loop specification begins with the keyword for which is followed by a <variable> and then the keyword in and a <sequence> followed by a colon (:). This line sets up the number of times the repetition will be repeated. What follows is a set of statements, indented (again, indentation is important), that are called a block that forms the body of the loop (stuff that is repeated).

When executed, the <variable> (which is called a loop index variable) is assigned successive values in the and for each of those values, the statements in the body of the loop are executed. A <sequence> in Python is a list of values. Lists are central to Python and we will see several examples of lists later. For now, look at the dance example above and notice that we have used the function range(10) to specify the sequence.

In [22]:
range(10)
Out[22]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The result of entering the range(10) is a sequence (a list) of ten numbers $0$ to $9$. Notice how range returns a sequence of values starting from $0$ all the way up to, but including, $10$. Thus, the variable i in the loop:

In [ ]:
for i in range(10):
    print(i)
    dance()

will take on the value 0 through 9 and for each of those values it will execute the dance() command.

A Dancing Robot

In [ ]:
# File: dance.py
# Purpose: A simple dance routine

# First import myro and connect to the robot

from myro import *
init()
 
# Define the new functions...

def yoyo(speed, waitTime):
    forward(speed, waitTime)
    backward(speed, waitTime)
    stop()

        
def wiggle(speed, waitTime):
    motors(-speed, speed)
    wait(waitTime)
    motors(speed, -speed)
    wait(waitTime)
    stop()

def dance():
    yoyo(0.5, 0.5)
    yoyo(0.5, 0.5)
    wiggle(0.5, 1)
    wiggle(0.5, 1)

# The main dance program
def main():
    print ("Running the dance routine...")
    for danceStep in range(10):
        dance()
    print ("...Done")

main()

Notice that we have used danceStep (a more meaningful name than i) to represent the loop index variable. When you run this program, the robot should perform the dance routine ten times. Modify the value specified in the range command to try out some more steps. If you end up specifying a really large value, remember that for each value of danceStep the robot will do something for $6$ seconds. Thus, if you specified $100$ repetitions, the robot will run for $10$ minutes.

In addition to repeating by counting, you can also specify repetition using time. For example, if you wanted the robot (or the computer) to do something for 30 seconds. You can write the following command to specify a repetition based on time:

for t in timer(10):
    <do something>
    <do something else>
    ...

The above commands will be repeated for 10 seconds. Thus, if you wanted the computer to say “Doh!” for 5 seconds, you can write:

In [2]:
from Myro import *
for t in timer(5): 
    speak("Doh!", 0)
Doh!
Doh!
Doh!
Doh!
Doh!
Doh!

In writing robot programs there will also be times when you just want the robot to keep doing its behaviors forever! While technically by forever we do mean eternity in reality what is likely to happen is either it runs out of batteries, or you decide to stop it (using the iPython stop button). The Python command to specify this uses a different loop statement, called a while-loop that can be written as:

while True:
   <do something>
   <do something else>
   ...

True is also a value in Python (along with False) about which we will learn more a little later. For now, it would suffice for us to say that the above loop is specifying that the body of the loop be executed forever!

Do This: Modify the dance.py program to use the timed loop as well as the while-loop. In the last case (while TRUE:) remember to use the stop button to stop the repetitions (and the robot).

As we mentioned above, repetition is one of the key concepts in computing. For example, we can use repetition to predict the world population in ten years by repeatedly computing the values for each year:

In [5]:
population = 6650000000
growthRate = 1.14/100.0
for year in range(10):
    population = population * (1 + growthRate)
    print(population)
6725810000.0
6802484234.0
6880032554.27
6958464925.39
7037791425.54
7118022247.79
7199167701.41
7281238213.21
7364244328.84
7448196714.19

That is, repeatedly add the increase in population, based on growth rate, ten times.

Do This: Modify the worldPop.py program to input the current population, growth rate, and the number of years to project ahead and compute the resulting total population. Run your program on several different values (Google: “world population growth” to get latest numbers). Can you estimate when the world population will become 9 billion?

Summary

This chapter introduced the basic structure of Python (and robot) programs. We also learned about names and values in Python. Names can be used to designate functions and values. The latter are also called variables. Python provides several different types of values: integers, floating point numbers, strings, and also boolean values (True and False). Most values have built-in operations (like addition, subtration, etc.) that perform calculations on them. Also, one can form sequences of values using lists. Python provides simple built-in facilities for obtaining input from the user. All of these enable us to write not only robot programs but also programs that perform any kind of computation. Repetition is a central and perhaps the most useful concept in computing. In Python you can specify repetition using either a for-loop or a while-loop. The latter are useful in writing general robot brain programs. In later chapters, we will learn how to write more sophisticated robot behaviors.

Myro Review

speak(<something>)

The computer converts the text in <something> to speech and speaks it out. <something> is also simultaneously printed on the screen. Speech generation is done synchronously. That is, anything following the speak command is executed only after the entire thing is spoken.

speak(<something>, 0)

The computer converts the text in <something> to speech and speaks it out. <something> is also simultaneously printed on the screen. Speech generation is done asynchronously. That is, execution of subsequent commands can be done prior to the text being spoken.

timer(<seconds>)

This is used to specify timed repetitions in a for-loop (see below).

Python Review

Values

Values in Python can be numbers (integers or floating point numbers) or strings. Each type of value can be used in an expression by itself or using a combination of operations defined for that type (for example, +, -, *, /, % for numbers). Strings are considered sequences of characters (or letters).

Names

A name in Python must begin with either an alphabetic letter (a-z or A-Z) or the underscore (i.e. _) and can be followed by any sequence of letters, digits, or underscore letters.

Input

Your program can ask the user a question using the input function:

input(<prompt string>)

This function prints out <prompt string> and waits for the user to enter some text. That text is returned as a string.

float(input(<prompt string>)) can be used to convert the user's inputted text into a number.

Main

from Myro import *
initialize("comX")

<any other imports>
<function definitions>
def main():
    <do something>
    <do something>
    ...
main()

This is the basic structure of a robot control program in Python. Without the first two lines, it is the basic structure of many Python programs.

print (<expression1>, <expression2>, ...)

Prints out the result of all the expressions on the screen. Zero or more expressions can be specified. When no expression is specified, it prints out an empty line.

<variable name> = <expression>

This is how Python assigns values to variables. The value generated by <expression> will become the new value of<variable name>.

range(10)

Generates a sequence, a list, of numbers from 0 up to and including 9. There are other, more general, versions of this function. These are shown below.

range(n)

Generates a sequence, a list, of numbers from 0 up to but not including n. There are other, more general, versions of this function. These are shown below.

range(n1, n2)

Generates a list of numbers starting from $n1 ... n2-1$. For example:

In [10]:
range(5, 10)
Out[10]:
[5, 6, 7, 8, 9]

range(n1, n2, step)

Generates a list of numbers starting from $n1 ... (n2-1)$ in increments of step. For example:

In [9]:
range(5, 10, 2)
Out[9]:
[5, 7, 9]

Repetition

for <variable> in <sequence>:
   <do something>
   <do something else>
   ...

for t in timer(<seconds>):
    <do something>
    <do something else>
    ...

while True:
   <do something>
   <do something else>
   ...

These are different ways of doing repetition in Python. The first version will assign <variable> successive values in <sequence> and carry out the body once for each such value. The second version will carry out the body for <seconds> amount of time. timer is a Myro function (see above). The last version specifies an un-ending repetition.

Exercises

1) Write a Python program to convert a temperature from degrees Celsius to degrees Fahrenheit. Here is a sample interaction with such a program:

Enter a temperature in degrees Celsius: 5.0
That is equivalent to 41.0 degrees Fahrenheit.

The formula to convert a temperature from Celsius to Fahrenheit is:

$ \Large{\frac{C}{5} = \frac{F-32}{9} }$,

where C is temperature in degrees Celsius and F is the temperature in degrees Fahrenheit.

2) Write a Python program to convert a temperature from degrees Fahrenheit to degrees Celsius.

3) Write a program to convert a given amount of money in US dollars to an equivalent amount in Euros. Look up the current exchange rate on the web (see xe.com, for example).

4) Modify the version of the dance program above that uses a for-loop to use the following loop:

In [ ]:
for danceStep in [1,2,3]:
    dance()

That is, you can actually use a list itself to specify the repetition (and successive values the loop variable will take). Try it again with the lists [3, 2, 6], or [3.5, 7.2, 1.45], or ["United", "States", "of", "America"]. Also try replacing the list above with the string "ABC". Remember, strings are also sequences in Python. We will learn more about lists later.

5) Run the world population program (any version from the chapter) and when it prompts for input, try entering the following and observe the behavior of the program. Also, given what you have learned in this chapter, try and explain the resulting behavior.

9) Rewrite your solution to Exercise 4 from the previous chapter to use the program structure described above.

10) You were introduced to the rules of naming in Python. You may have noticed that we have made extensive use of mixed case in naming some entities. For example,waitTime. There are several naming conventions used by programmers and that has led to an interesting culture in of itself. Look up the phrase CamelCase controversy in your favorite search engine to learn about naming conventions. For an interesting article on this, see The Semicolon Wars (http://www.americanscientist.org/issues/pub/the-semicolon-wars).

11) Experiment with the speak function introduced in this chapter. Try giving it a number to speak (try both integers and floating point numbers). What is the largest integer value that it can speak? What happens when this limit is exceeded? Try to give the speak function a list of numbers, or strings, or both.

12) Write a Python program that sings the ABC song: ABCD…XYZ. Now I know my ABC’s. Next time won’t you sing with me?


Previous: [Chapter 2](Chapter 2.ipynb)[Learning Computing with Robots](Learning Computing with Robots.ipynb)Next: [Chapter 4](Chapter 4.ipynb)