Download - Python scripting kick off
Welcome to the: "Oh, no!
Yet another programming language!"
Python scripting Kickoff
Andrea GangemiDecember 2008
What's cool in Python (IMHO)• A Free, easy to learn High Level OO Language • JIT Interpreter• Powerful standard library, string management... • Huge collection of external libraries and docs• Multiplatform• List Comprehension• Native Exception handling
HistoryGuido Van Rossum Dutch Programmer and Monty Python fan
• 0.9.0 (1991) o exception handling, list, dict ...o running on Amoeba distributed OS
• 1.x (1994)o Lambda Calculus, Complex numbers ...o running on PC o GPL license
• 2.x (2000)o List Comprehension ... o Running ... almost everywhere.
• 3.x AKA Python 3000 or Py3k (3 Dec 2008)
Installing Python
• GNU/Linux Systems:Usually already installed, just type "python" at the shell prompt
• Windows:1.http://www.python.org/download/ Official Site2.http://www.cygwin.org/cygwin/ Cygwin3.http://www.activestate.com ActivePython
1. For other OS or details:1.http://diveintopython.org Dive into Python free book• http://www.google.com/search... Google :)
• You can also try Python on-line at:http://try-python.mired.org/
Python Shell
To Exit:Ctrl-D In Unix: "End of File" And Now for Something Completely Different ...some practical examples
Variables• Variables are NOT declared
i.e. type is defined when you assign the value for the first time.This also mean you have to assign a value before using it and some potential pitfalls.
• Multiple Assignment >>> x = y = z = 42
• Python implements powerful string manipulation methodso negative indexo concatenationo slicing o strip, find
click here for further References about this and next slides
Compound data types (1/2)• List: A collection of items whatever they are
>>> list_example = [ 1, "helloworld" , 3.14 , 42+12j ]>>> list_example[1, 'helloworld', 3.1400000000000001, (42+12j)]o Can be sliced, nested, items can be inserted/removed o Lists have methods
• Tuples: a collection of items separated by comma >>> tuple_example = 1, "helloworld" , 3.14 , 42+12j>>> tuple_example(1, 'helloworld', 3.1400000000000001, (42+12j))o Faster than Lists but cannot be modifiedo Can be sliced (obtaining a new tuple)o Used for print formatting (Python <= 2.x)
• Tuples can be converted into list and viceversa
Compound data types (2/2)• Set: an unordered collection with no duplicate elements.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'banana']>>> fruit = set(basket) set(['orange', 'pear', 'apple', 'banana'])o Useful for eliminate duplicates or membership testing
• Dictionaries: an unordered set of keys, which can be any immutable type.>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}>>> tel['jack']4098o dict() can be used to build dictionary from key-value
tuples
List Comprehension and operators• Operators:
o Boolean comparison, Arithmetic operation and Bit manipulations are similar to C language
o Logical operations are: "and", "not", "or" • List Comprehension: Wikipedia: "A list comprehension is a syntactic construct [...] for creating
a list based on existing lists.
>>> vec = [2, 4, 6]>>> result = [(x, x**2) for x in vec]What results looks like?
Try it! Let's see how I used list comprehension in Barblery
Flow Control
• if, for and while Python does not uses parentheses to identify code blocks, indentation is Python’s way of grouping statements.o Coder is forced to write readable code (more or less)
• >>> for x in range (2,5):... print 'x is ' , x... x is 2x is 3x is 4
Note the use of keyword "in" and builtin function range()
SPAM Break
Functionsdef function_name[(parameters)]: """Optional document string""" # Code here # ... [return value]
Example:
def makedir(stringdate): dirname = stringdate[:4]+stringdate[5:7]+stringdate[8:10] if os.path.exists(dirname) and os.path.isdir(dirname): created = False else: os.mkdir(dirname) created = True return dirname,created
Let's comment together this function
More about functions
• Functions supports default operators.• Functions can also be called using keyword arguments • End of function is detected by indentation.• return value can be a single value or a tuple.• To pass a tuple to a function requiring separate arguments
use the "*" operator:>>> args = [3, 6]>>> range(*args) [3, 4, 5]
Exception handlingIn order to nicely manage unexpected exception Python provides try, except, finally statementsimport systry: s = raw_input('Enter something --> ')except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the programexcept: print '\nSome error/exception occurred.' # here, we are not exiting the programprint 'Done'
If finally is present, it specifies a cleanup handler
Modules
• Modules are files containing functions definitions and statements.
• File name is module name and .py as extension.• Use "import" to import module • You can import only some functions from the modules:
from time import gmtime, strftime
• Modules always have a variable __name__ containing module name.
Let's see some real scripts... Click here for a scripting tutorial
Script Sample#!/usr/bin/env python
def function_divide(numerator, denominator): try: result = numerator / denominator print 'x/y=', result except ZeroDivisionError: print 'Divide by zero' except: print 'Invalid operation'
if __name__ == '__main__': while True: input_data = input('type 2 numbers separated by comma: ') if len(input_data) == 2: function_divide(*input_data) else: break
Some Interesting base modules
• optparsepowerful command line option parser
• osOS routines for Mac, NT or Posix
• shutilUtility functions for copying files and directory trees.
• timeTime access and conversion
• urllib2URL access library
• commandstake a system command as a string and return output
Modules modules modules Scripting scripting scripting...Most of the time spent to code in Python is to search for something that already does what you need...
Python Serial Port Extension
Useful links
• Python official documentation • Learn to Program using Python, developer.com • Dive into Python • Thinking in Python • Python Istantaneo (Italian)• IBM Discover Python• A byte of Python • urllib2 - The Missing Manual • Python: 50 modules for all needs AND ...
• Monty Python on wikipedia
Thank you
Andrea Gangemi
email: [email protected]: +39 340 5987091 skype: andreagangemi
linkedIn: www.linkedin.com/in/andreagangemi