background preloader

Python: Lambda Functions

Python: Lambda Functions
Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce(). This piece of code shows the difference between a normal function definition ("f") and a lambda function ("g"): As you can see, f() and g() do exactly the same and can be used in the same ways. The following code fragments demonstrate the use of lambda functions. The above code defines a function "make_inrementor" that creates an anonymous function on the fly and returns it. You can now create multiple different incrementor functions and assign them to variables, then use them independent from each other. The following takes this a step further. In the second example, map() is used to convert our list.

Python: List Comprehensions Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do. The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics. You probably know things like the above from mathematics lessons at school. This is how you do the above in Python: I'm sure you want to see a more complicated example. :-) The following is yet another way to compute prime numbers. NB: You can nest list comprehensions inside of each other, so you could write the above example with a single statement (without the need for the temporary variable "noprimes"). Of course, list comprehensions don't only work for numbers. The following works on a list of strings and produces a list of lists. The above example also demonstrates that you can do exactly the same thing with map() and a lambda function.

PEP 8 -- Style Guide for Python Code Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead.

Python Exception Handling Techniques - Doug Hellmann Error reporting and processing through exceptions is one of Python’s key features. Care must be taken when handling exceptions to ensure proper application cleanup while maintaining useful error reporting. Error reporting and processing through exceptions is one of Python’s key features. Throwing and Catching The statements used to deal with exceptions are raise and except. The arguments needed by the exception class vary, but usually include a message string to explain the problem encountered. If the exception is left unhandled, the default behavior is for the interpreter to print a full traceback and the error message included in the exception. For some scripts this behavior is sufficient, but it is nicer to catch the exception and print a more user-friendly version of the error. In the example above, all exceptions derived from Exception are caught, and just the error message is printed to stderr. $ python catching.py ERROR: this is the error message Logging Exceptions See also

Python: interfacing with an arduino | Stealthcopter.com So what is an arduino? An arduino is an open source open hardware programmable controller with several inputs and outputs. The image below shows an Ardunio Dicemella. Ardunio Dicemella Annotated Photo It (Arduino Dicemella) has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a power jack, an ICSP header, and a reset button. They are very useful for people who know how to program but have little experience with hardware interaction. Programming the arduino This post will not contain in-depth detail on how to program the arduino, instead focussing briefly on setting up serial (over serial or usb cable) communications in order to talk to a python script. Code example Arduino LED switch circuit off Arduino LED switch circuit on Now we add a few lines to enable the writing of information from our arduino over the serial connection. Serial write example Serial read example Interaction with python import serial

Make Yahoo! Web Service REST calls with Python Python provides a number of modules for performing HTTP requests. This HOWTO describes how to perform GET and POST requests using the urllib and urllib2 modules from the Python standard library. Simple GET requests The simplest way of retrieving data from a URL uses the urllib.urlopen function: import urllib url = ' u = urllib.urlopen(url) # u is a file-like object data = u.read() This can be condensed in to a single line: data = urllib.urlopen(url).read() This is fine for quickly retrieving some data, but does not give you the ability to easily distinguish between normal page retrievals and 404 or 500 errors. import urllib2 try: data = urllib2.urlopen(url).read() except urllib2.HTTPError, e: print "HTTP error: %d" % e.code except urllib2.URLError, e: print "Network error: %s" % e.reason.args[1] An HTTPError is thrown if the server returns a status code other than 200 (OK) or an HTTP redirect. Simple POST requests Some APIs require you to make POST requests.

Arduino Tutorial - Lesson 3 - Breadboards and LEDs You've started modifying sketches, and played a bit with the onboard LED (or if you have an NG, an LED you added). The next step is to start adding onto the hardware component of the Arduino. We will do this by adding a solderless breadboard to our setup, connecting up new parts with wire. Solderless breadboards are an important tool in your quest for electronics mastery. They allow you to make quick circuits, test out ideas before making a more permanent Printed Circuit Board. They're also inexpensive and reusable.. Basically, a chunk of plastic with a bunch of holes. In the images above you can see how there are two kinds of metal strips. In this lesson, we will show pictures of both the tiny breadboard on a protoshield and also using a 'standard' breadboard without a shield. Warning! Distressing as it may sound, solderless breadboards can be very flakey, especially as they age. To use the breadboard, you'll need jumper wires. Nick the insulation, then pull it off. Behold...a resistor!

Arduino Tutorial - Learn electronics and microcontrollers using Arduino! So, I get two or three emails a day, all basically asking the same thing: "Where can I learn about electronics?" In general, most of these people have seen some of my projects and want to be able to build similar things. Unfortunately, I have never been able to point them to a good site that really takes the reader through a solid introduction to microcontrollers and basic electronics. I designed this tutorial course to accompany the Arduino starter pack sold at the Adafruit webshop. Follow these lessons for happiness and prosperity. Lesson 0 Pre-flight check...Is your Arduino and computer ready? Here are some recommended tools: If you need to get any soldering done, you may also want.... All of the content in the Arduino Tutorial is CC 2.5 Share-Alike Attrib. Love it? To some extent, the structure of the material borrows from: The impressively good "What's a microcontroller?" "Spooky Arduino" - Todbot's excellent (if fast-paced!)

Getting Started with WSGI written on Monday, May 21, 2007 I finally finished the written matura and have some more time to work on projects and write articles. One of the things I wanted to write for a long time is a WSGI tutorial that does not require a specific framework or implementation. So here we go. What's WSGI? Basically WSGI is lower level than CGI which you probably know. WSGI is specified in the PEP 333 and adapted by various frameworks including the well known frameworks django and pylons. If you are too lazy to read the pep 333 here's a short summary: Because that's a lot of information let's ignore it for now and have a look at a basic WSGI application: Extended Hello World Here a simple, but not too simple example of a WSGI application that says Hello World! As you can see the start_response function takes two arguments. But how to start that application now? Just add this to your file: When you now start the file you should be able to get a Hello John! Path Dispatching Now that's a bunch of code. #!

Related: