########################################################################## # Python Programming # # Anuradha Weeraman, 04 November 2003 # # $Id: python.txt,v 1.1 2004/06/02 21:17:54 anuradha Exp $ # ########################################################################## Python interactive interpreter : >>> print "hello world!" hello world! >>> import sys >>> sys.exit(1) or >>> ^D To run a script and enter interactive mode : python -i script.py Arguments passed to the python program are set as strings in sys.argv When no script and no argument is given, sys.argv[0] is an empty string. Example of an interactive script: >>> b = 1 >>> if b: ... print "b is set" ... b is set >>> On BSD'ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line #!/usr/bin/env python You can set an environment variable PYTHONSTARTUP to point to a python script that starts every time the interpreter is invoked interactively, similar to .profile in the shell. Here the sys.ps1 and sys.ps2 can be set to customize the python interactive shell prompt. To execute the startup script from within a python script : import os filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): execfile(filename) Comments in python start with "#" and extend to the end of the line. It may appear at the beginning or end of a line but not within a string literal. The interactive python can also be used as a simple calculator. Complex numbers are also supported; imaginary numbers are written with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be created with the "complex(real, imag)" function. In interactive mode, the last printed expression is assigned to the variable _. String literals can span multiple lines by escaping the newlines. A string can be subscripted. The first character is index 0. There is no special string type. Its basically an array of characters, like in C. Python strings cannot be changed. Assigning to an indexed position results in error. An index that is too large is replaced by the string size. Negative indices start counting from the right. +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 The built-in function len() returns the length of a string. Any non-zero value is evaluated by Python as true. Some simple syntax : >>> width = 20 >>> x = y = z = 0 >>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5 >>> tax = 17.5 / 100 >>> price = 3.50 >>> price * tax 0.61249999999999993 >>> price + _ 4.1124999999999998 >>> round(_, 2) 4.1100000000000003 >>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.' print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """ >>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '' >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' >>> word[:2] + word[2:] 'HelpA' >>> word[:3] + word[3:] 'HelpA' >>> word[-2:] # The last two characters 'pA' >>> word[:-2] # All but the last two characters 'Hel' >>> word[-0] # (since -0 equals 0) 'H' >>> u'Hello World !' # unicode string u'Hello World !' >>> u'\u0041nu' u'Anu' >>> u"äöü".encode('utf-8') '\xc3\xa4\xc3\xb6\xc3\xbc' >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8') u'\xe4\xf6\xfc' >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> 3*a[:3] + ['Boe!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] >>> a[2] = a[2] + 23 # list elements aren't immutable >>> # Replace some items: ... a[0:2] = [1, 12] >>> a [1, 12, 123, 1234] >>> # Remove some: ... a[0:2] = [] >>> a [123, 1234] >>> # Insert some: ... a[1:1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> a[:0] = a # Insert (a copy of) itself at the beginning >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] >>> a = [1, 2, 3, [ 5, 5, 5 ] ] >>> a [1, 2, 3, [5, 5, 5]] >>> a[3] [5, 5, 5] >>> for i in a[3]: ... print i ... 5 5 5 >>> >>> line1 = 'line1' >>> line2 = 'line2' >>> print line1; print line2 line1 line2 >>> print line1, ; print line2 line1 line2 ---===== Control Flow =====--- If Statements >>> x = int(raw_input("Please enter a number: ")) >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ... For Statements >>> # Measure some strings: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... cat 3 window 6 defenestrate 12 It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, i.e., lists). If you need to modify the list you are iterating over, e.g., duplicate selected items, you must iterate over a copy. The slice notation makes this particularly convenient: >>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate'] Chapter 4.3