32
And PyLNP for the RCX By: Eric Cranmer and Nick Blake

And PyLNP for the RCX

Embed Size (px)

DESCRIPTION

And PyLNP for the RCX. By: Eric Cranmer and Nick Blake. Python?... Isn’t that a snake?. NO!.. It is actually named after the show: ‘Monty Python’s Flying Circus’ on BBC A programming language that is: Interpreted Interactive Object-Oriented Similar to Java, Perl, and Scheme - PowerPoint PPT Presentation

Citation preview

Page 1: And PyLNP for the RCX

And PyLNP for the RCX

By: Eric Cranmer and Nick Blake

Page 2: And PyLNP for the RCX

Python?... Isn’t that a snake?

• NO!.. It is actually named after the show:– ‘Monty Python’s Flying Circus’ on BBC

• A programming language that is:• Interpreted• Interactive• Object-Oriented

• Similar to Java, Perl, and Scheme• Developed in 1990 by CWI in Amsterdam• Now owned by Python Software Foundation

Page 3: And PyLNP for the RCX

The Skin of the Snake

• Python 2.4 - FREE!!

• Interactive – like Scheme, you can run certain parts of code

• Large standard library• Eg: Math functions, regular expressions, file IO

( Software )

Page 4: And PyLNP for the RCX

• On UNIX, type python to start command-line interpreter– python –c command [arg] …

– Ex: python –c “import sys; sys.exit()”– Ex: python –c “print ‘hello’”

• If errors occur, HELPFUL error messages are displayed

The Skin of the Snake (cont..)( Software )

Page 5: And PyLNP for the RCX

The Soul Within the Beast

• Structure• Data Types• Variables and Scope• Conditionals and Loops• Functions• Parameter Passing / Assignment• Garbage Collection• Classes• I/O• Multi-Tasking

( The Language Itself )

Page 6: And PyLNP for the RCX

Structure

• No Special End-of-Line character like ‘;’

• Comments are denoted by the ‘#’

• Indentation is a must• YES…. you have to go by the standards• Throws IndentationError if you don’t

Page 7: And PyLNP for the RCX

Numbers• Arithmetic is infix and operators have regular precedence that

we are use to• (50-5*6)/4 outputs 5

• Integer division does floor function• Floating point supported

• 4 * 2.5 / 5 outputs 2.0• Complex numbers also

• (2+3j)*4 outputs (8+12j)• z.real and z.imag

• Conversions done with functions like:• float(), int(), and long()

• Round decimal numbers using round()• round(113.0625, 2) outputs 113.06

Page 8: And PyLNP for the RCX

Strings• Enclosed by single or double quotes• \ means String continues on next line• Triple quotes can be used also ( ” ” ” ) or ( ‘ ‘ ‘ )• Raw and Unicode Strings• Concatenation with +, Repetition with *• No character type• Strings are indexed

• word = ‘help’; word[3] #outputs ‘p’

• word[0:2] #outputs ‘he’ - same as word[:2]

• word[:200] #outputs ‘help’

• Negative indices go backwards• Can get the length of a String using len()

Page 9: And PyLNP for the RCX

Lists

• Defined within [ ] and don’t need to have same type• Indices and concatenation just like Strings• Length can be found using len()• Can nest lists within other lists• in statement

• Examples:• >>>list = [ 12, ‘eric’, 23.3, ‘nick’ ]• >>>list[1] = ‘bob’ # list now is [ 12, ‘bob’, 23.3, ‘nick ]• >>>other = [ 2, list ]• >>>other[1][0]• 12

Page 10: And PyLNP for the RCX

Lists (cont.)

• append(x)• extend(L)• insert(i,x)• remove(x) – remove item x

• pop([i]) – remove and return item at index i

• index(x) – index of first occurrence

• count(x) - # of times in the list

• sort() – sort the items in the list

• reverse() – reverse the list• del <list-name>[ ] – deletes an element from a list

Page 11: And PyLNP for the RCX

Example

>>> # Fibonacci

. . . a, b = 0, 1

>>> while b < 10:

. . . print b # if you put comma at end of this line, will print on ONE line

. . . a, b = b, a+b # multiple assignment

. . .

1

1

2

3

5

8

Page 12: And PyLNP for the RCX

Variables and Scope• Variables assigned values by ‘=‘• Can assign many variables at once

• x = y = z = 10 # x,y, and z all equal 10• After you type an expression, its value is stored into _

• >>>10 * 13 #outputs 130• >>>_ / 2 #outputs 65

Page 13: And PyLNP for the RCX

if Statement

>>>x = int(raw_input(“Integer: ”))>>>if x < 50:. . . x = 0. . . print ‘small number’. . . elif x == 1000:. . . print ‘thats a BIG number!’. . . else:. . . print ‘large number’. . .

Page 14: And PyLNP for the RCX

for Statement

>>>list = [‘eric’, ‘wow’, ‘hello’]

>>>for item in list:

. . . print item, len(item)

. . .

eric 4

wow 3

hello 5

Page 15: And PyLNP for the RCX

Other statements…

• range() function• >>>range(3)• [0,1,2]

• break – same as in C

• continue – same as in C

• pass – does NOTHING! (seriously)

Page 16: And PyLNP for the RCX

Defining Functions

• Keyword: def <function-name>(<params>):• Global variables can be referenced in functions

but can NOT be assigned new values• Arguments passed using call by value• return statement supported• Default argument values

• def function(a, b=4, c):

• Keyword arguments• def func(a, b=“hello”, c=25):• ^ can be called by: func(10), func(b=“cool”, “man”), etc…• ^ can’t do something like: func(a=10, 20)

Page 17: And PyLNP for the RCX

Lambda

• Just like in Lisp and Scheme

>>>def add_em(n, m):. . . return lambda n,m: n+m. . .>>>f = add_em(0,0)>>>f(2,3)5

Page 18: And PyLNP for the RCX

Classes

class Test:

"This is a test class."

def __init__(self):

print self.__doc__

print self

test = Test()

Class definitions are straight forward.

An optional string can follow the classdefinition, it is normally used to describethe class.

To access this string, used the __doc__attribute.

The method __init__(self) acts as a constructor, and is called upon thecreation of a class instance. It is alsooptional.

Page 19: And PyLNP for the RCX

Inheritanceclass Car:

"A car."doors = 4def __init__(self):

print self.__doc__

print self.doors

def printStuff( self ):print self.doors

class Sedan(Car):"A car that is a sedan."def __init__(self):

Car.__init__(self)

car = Car()sedan = Sedan()sedan.printStuff()

To declare inheritance, simply put all superclasses in parenthesis following the classname, separated by commas if multipleinheritance.

To call the __init__() of the super class,just call it using the class name, and passthe instance of the current class.

Python allows for diamond inheritance, butas in most cases, it is better to find alternatemodels, diamond inheritance has many problems.

Page 20: And PyLNP for the RCX

File I/O

Start by creating a file object.

file = open( filename, mode )

filename is a string referring to the location of the file.

mode can be either ‘r’ for read only, ‘w’ for write only, or ‘r+’ for read and write. This parameter is optional, and it will be assumed read only if omitted.

Page 21: And PyLNP for the RCX

File I/O - Reading

You can use read(), readline(), or readlines() to read information from a file object.

read() – returns the entire text of the file.

readline() – returns the first unread line of the file each time it is called.

readlines() – returns a list of all the lines in the file.

Page 22: And PyLNP for the RCX

File I/O - Writing

You can only write strings, and to do so use:write(str)

However, the pickle module is similar to Java’s object serialization.

pickle.dump(object, file)

obj = pickle.load(file)

Page 23: And PyLNP for the RCX

File I/O – Additional Methods

seek( offset, position )

offset is an integer value

position is either 0, for the start of the file, 1, for the current position, or 2, for the end of the file.

close()

Closes the file object, and frees any resources it is taking. No further methods may be invoked on it.

Page 24: And PyLNP for the RCX

Multi-threading

Very similar to Java’s threads.

You must first import threading

Create an object that inherits from the threading.Thread object, making sure to call the threading.Thread.__init__(self) method in your classes __init__(self)

Next, override the run(self) method, and you have yourself a thread.

Page 25: And PyLNP for the RCX

Multi-threading

Call start() on your thread object to start it, the main thread will continue to run.

Call join() on your thread object to have the main thread wait until the thread objects finishes execution before continuing.

Synchronization can be accomplished through using a single thread with a Queue in it. Instead of requesting something from a resource, all threads instead request it from this one thread, which then access the resource itself, and sends it back to the thread that initially requested it.

Page 26: And PyLNP for the RCX

Why to use it.

• It is a high-level general-purpose programming language, useful for solving a very large range of problems.

• Enforces good standards.• It is very extensible, there are many third-

party modules, and the option is always there to make your own.

• Existing modules make tasks difficult in other languages very simple.

Page 27: And PyLNP for the RCX

How to get it.

It is simple…

Just go to http://www.python.org

They also have links to where to find any module you would need.

Page 28: And PyLNP for the RCX

Getting it running.

It is a good idea to add python.exe into your environment variables.

Next, simply run:

python sourceFile.py

You could also run the python interpreter and use the language interactively.

Page 29: And PyLNP for the RCX

Does it work with Legos and the RCX?

…to a degree.

PyLNP is a module that allows for communication over the IR tower to LegOS / brickOS.

Homepage of PyLNP:http://www.hare.demon.co.uk/lego/pylnp.html

Page 30: And PyLNP for the RCX

PyLNPPyLNP is linux only

Similar to UDP for IR

Has very poor documentation

There must be a program on the RCX written in either C or C++ ready to interpret the messages sent by PyLNP.

Page 31: And PyLNP for the RCX

Sample PyLNPimport lnp

#Ask the RCX if it is

# active.

lnp.iwrite(‘active?’)

#Read the response

# given

print lnp.iread()

This small program loads the PyLNP module ( lnp )

It then writes a message to the RCX over the IR tower.

A program on the RCX (running LegOS / brickOS) receives the message, and returns one of its own, in this case it may be “Yes.”

The program then prints theresponse, again in this case, “Yes.”

Page 32: And PyLNP for the RCX

For more information..

Go to www.python.org !

It has endless tutorials and documentation.

It has links to most third-party modules.

It has links to developer’s sites, projects, and forums.