Error: no such theme PatternSkinTheme
You are here: Foswiki>Main Web>CSAndRobotsExco>ExcoLab2 (2013-02-20, KateIngersoll)EditAttach

Robots Part 2

Mini-lecture:

Function: A way to give a name to a list of commands, or a way to generalize similar commands.

It's important that functions are passed meaningful/appropriate values. For example, consider the (non-Python) function:

pie (fruit)

Pie is the title of the function. Fruit is the variable that is entered. To complete the command you would put in the function name and the variable you want with it

pie (blackberry)

pie (apple)

pie ( broccoli)

broccoli would not work, because we know it to be a vegetable. So it would probably return an error message or break the computer.

Lab:

Setting up a code directory

Last week, most of you did not have MathLan accounts, so we had you do your exercises in the directory 'walker'. Now that you have accounts, you will find it useful to create a directory to store your code for this class on your own account.

1. Open the terminal (click on the black box icon in the menu bar)

2. Type pwd into the terminal. This prints the current [or working] directory. You should see something like '/home/my-username'

3. Create a directory (a folder) for this exco. You can store it anywhere, but we'd recommend storing it either in your main folder (where you are now), or on your Desktop. To move to the Desktop, you can type: 'cd ./Desktop' Remember that cd stands for change directory, and '.' stands for the current directory. You can use pwd to make sure that this command worked. If it did, pwd should now say '/home/username/Desktop'. Once you are in the folder you want to put your new directory into, type mkdir name-of-file into the terminal.

4. Aside: If you ever want to learn more about terminal commands, you can type man command-name into the terminal, and hit enter. This brings up a description of the command, (although the documentation might be very dense & wordy.) Hit 'q' to return to the main terminal.

5. Move into your new directory: cd ./exco (if exco if the name of your new directory.)

6. Now, you will copy the files needed to command the Scribbler robot from the 'walker' directory into your file. Type cp -R /home/walker/myro . Don't forget the period!

7. Aside: This last command instructs the computer to copy (cp) the myro folder found in /home/walker into the current directory (represented by the period). The '-R' symbol is an optional message (called a flag) to the 'cp' command: it tells cp to copy everything within the myro folder, including all sub-folders and files. This flag is needed when copying an entire folder/directory (as opposed to copying a single file.)

Importing functions

In this lab, you will be writing your own functions, and then using these functions in the python terminal. Let's begin with a very simple function to see how this works.

1. In your terminal window, connect to the robot:

--> type python

--> type from myro import *

--> type init("/dev/rfcomm0")

You should get a message from the robot, saying "Hello, I'm ___". If so, you're good to go.

2. Open a new terminal window, and use cd to move to your exco folder.

3. Type emacs lab2_v1.py & into the terminal. A new window should pop up. This command tells the computer to open up the program 'emacs', which is used to edit code files, similar to how Word is used to edit text files, with the new document 'lab2.py'. The '.py' extension declares the file a python file, written in the Pythin programming language.

4. Let's write a function in this file. Here's a sample program I wrote. Can you figure out what it does?

from myro import *

def myprint():
print "Hello, world!"
print "Good to meet you!"
print "bye"

Things to note:

--> every function in Python starts with the keyword def (short for define).

--> After def comes the name of the function, followed by parentheses, and a colon.

--> On the following lines, there's the body of the function: the commands that you want to issue every time the function is used. The commands are written in order, top to bottom.

--> REALLY IMPORTANT: Each command MUST be indented. This indentation tells the computer that those lines are part of the definition. Because of the way this page is saved, you don't see this indentation, so take our word for it-> indent every line after the definition to the same level of indentation as your function name. Or, hit 'tab' in emacs, and it will indent for you.

--> The file MUST begin with the line 'from myro import *' (we'll get to this soon.)

Format:

def function_name():

command1

command2

etc

5. Copy and paste the function above into emacs, and save the file (click on the button with the red arrow.)

6. Now, to call this function, go back to the terminal with the python shell. Type from lab2 import * . This command tells python to read (and use) all the functions (* is shorthand for 'all') in the python folder lab2.

7. Type myprint() into the terminal window. What happens? Try it again. Now, edit the print statements in test.py, and import test.py again. Type in myprint(). What happens?

8. As you may have noticed, even when you edit the test.py file, myprint() still returns the same print statements. This is a quirk of Python: in a session, it only allows you to import a file once, and will use the definitions from that original import. So, what do you do if you want to make changes to a file? You could close the Python shell (with Ctrl-D), and open it again, and then import your updated definitions, but then you'd also need to re-connect to the Scribbler robot, which would be time-consuming. Another option is to make your changes, and then use "Save as" to save them to a new file, and then import that new file (so could have test_v1.py, test_v2.py, test_v3.py, etc). This way, you have a record of your work, which can be nice. Once you get a version you're happy with, you can go back & delete the older versions.

9. Aside: Does the from lab2 import * command look familiar? It should! We start each lab session with the command 'from myro import *'. Now, you can understand what this command does: it imports all the functions like forward, turnRight, turnLeft, rotate, and so on, that you've been using in lab, from the myro directory, where the definitions of these functions are stored.

10. Summery:

To define functions, open emacs with the command 'emacs new-file.py &' in a NORMAL terminal, and write your functions in this file. Remember to start each file with 'from myro import *'

You can define as many functions as you like in a file! You may want to store similar functions together in one file.

To use functions, import the definitions with the command 'from new-file import *' in the PYTHON SHELL.

To call functions, type the function name, followed by parentheses.

Your First Functions

1. To get practice with importing functions, write your own function using some of the commands given below, and call your function in the Python shell. Ask the lab instructors for help if you get stuck.

Speed- any number from -1 to 1

backward(SPEED)
backward(SPEED,SECONDS)


forward(SPEED)
forward(SPEED,TIME)

rotate(SPEED)

stop()

turnLeft(SPEED)
turnLeft(SPEED,SECONDS)

turnRight(SPEED)
turnRight(SPEED,SECONDS)

wait(SECONDS)

Functions with Parameters

So far, you've been writing functions that are just lists of commands, telling the computer to do a series of instructions in order. However, we can do more with functions- we can write functions that take parameters. For example, I have this series of functions in a file:

from myro import *

def rotate_1sec():
rotate(.5)
wait(1)
stop()

def rotate_2sec():
rotate(.5)
wait(2)
stop()

def rotate_3sec():
rotate(.5)
wait(3)
stop()

They seem very repetitive, don't they? Every function is exactly the same, except that I give a different number to the command wait(seconds) each time. Consider this definition:


def my_rotate(sec):
rotate(.5)
wait(sec)
stop()

1. Copy these functions into a new file, and import it into the python shell. See if you can guess how my_rotate(sec) works. Then, type my_rotate(3) into the shell. Experiment giving my_rotate different numbers. The way this definition works is that, when you call the function, 'sec' is replaced by the number you provide, so with the call my_rotate(5), the computer interprets the function as the commands to:

rotate(.5)
wait(5)
stop()

The symbol 'sec' is called a parameter to the function. You can write functions with as many parameters as you want, separated by commas (as you've seen with other functions, like turnRight(speed, seconds).

Inefficient Functions

Here is a function that are relatively inefficient; we want functions to be efficient so that they run fast and do the job in as little steps as possible. (They use less resources this way). Try and edit the functions so that they are more efficient.

1. Consider this function PythonRepetitiveEx1. Re-write this function to do the same thing in fewer lines of code. Remember that functions can call other functions--for example, my_rotate calls rotate(speed) and wait()--so your functions can call other functions that you've written, as long as you have them in the same file, or import them into the file.

a) Try to figure out what the function does, before running it.

b) Run the program, make observations.

c) Re-write the program in as few lines of code as possible. Use descriptive function names. Use '#' to make comments in the code.

d) Extra: run your finished program on paper, using the sharpie to draw the path of the Scribbler.

2. Extra: re-write this function, PythonRepetitiveEx2, using the same methods as you used in part (1). For extra extra, draw the final path on paper.

-- AdrianaHurley - 2013-02-19
Topic revision: r4 - 2013-02-20, KateIngersoll
 

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback