Download document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
• Developed in 1990 by CWI in Amsterdam
• Now owned by Python Software Foundation
The Skin of the Snake
( Software )
• Python 2.4 - FREE!!
• Interactive – like Scheme, you can run
certain parts of code
• Large standard library
• Eg: Math functions, regular expressions, file IO
The Skin of the Snake (cont..)
( Software )
• On UNIX, type python to start commandline interpreter
– python –c command [arg] …
– Ex:
– Ex:
python –c “import sys; sys.exit()”
python –c “print ‘hello’”
• If errors occur, HELPFUL error messages
are displayed
The Soul Within the Beast
( The Language Itself )
•
•
•
•
•
•
•
•
•
•
Structure
Data Types
Variables and Scope
Conditionals and Loops
Functions
Parameter Passing / Assignment
Garbage Collection
Classes
I/O
Multi-Tasking
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
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
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]
• word[0:2]
• word[:200]
#outputs ‘p’
#outputs ‘he’ - same as word[:2]
#outputs ‘help’
• Negative indices go backwards
• Can get the length of a String using len()
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
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
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
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
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’
...
for Statement
>>>list = [‘eric’, ‘wow’, ‘hello’]
>>>for item in list:
...
print item, len(item)
...
eric 4
wow 3
hello 5
Other statements…
• range() function
• >>>range(3)
• [0,1,2]
• break – same as in C
• continue – same as in C
• pass – does NOTHING! (seriously)
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)
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
Classes
Class definitions are straight forward.
An optional string can follow the class
definition, it is normally used to describe
the class.
To access this string, used the __doc__
attribute.
The method __init__(self) acts as a
constructor, and is called upon the
creation of a class instance. It is also
optional.
class Test:
"This is a test class."
def __init__(self):
print self.__doc__
print self
test = Test()
Inheritance
To declare inheritance, simply put all super
classes in parenthesis following the class
name, separated by commas if multiple
inheritance.
To call the __init__() of the super class,
just call it using the class name, and pass
the instance of the current class.
Python allows for diamond inheritance, but
as in most cases, it is better to find alternate
models, diamond inheritance has many
problems.
class Car:
"A car."
doors = 4
def __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()
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.
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.
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)
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.
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.
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.
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 thirdparty modules, and the option is always
there to make your own.
• Existing modules make tasks difficult in
other languages very simple.
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.
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.
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
PyLNP
PyLNP 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.
Sample PyLNP
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 the
response, again in this case, “Yes.”
import lnp
#Ask the RCX if it is
# active.
lnp.iwrite(‘active?’)
#Read the response
# given
print lnp.iread()
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.