# How to learn a new programming language in 1 hour: # My first Python program! # Python is found at Hofstra at /shared/csc/local/bin/python # Type 'which python' first to see if you're already set up. # Run this program with 'python first.py', or type 'python' and use # it like the scheme interpreter. # tail-recursive n! function (now defined as interior function) def factorial(n) : def fact(n,ax) : # local function like in Scheme/Pascal if n<2 : return ax; # note the colon else : return fact(n-1,ax*n); return fact(n,1) # There are no delimiters in python, just indentation # testing: print "the factorial of 5 is ", factorial(5); ###### linked lists (or arrays) x=[1,2,3,"ab","cd"]; # semicolons are optional print x[3] # prints "ab" x = x + [4,5,6] print "x appended:", x def sum(l): # sum of list ax = 0; # ax is local to sum function for i in range(0,len(l)) : # range similar to Pascal/Ada ax = ax+l[i]; # len is built-in function for length return ax; print "sum of list is", sum([2,4,6]); ###### hash tables: (python is to perl what C# is to Java? hope not!) y={'scheme':1, 'perl':2, 'Java':3}; print y["perl"], ":look ma, no types"; y['perl'] = 4; print y["perl"]; # note the uses of ' and " ###### Swaping two vars was never easier: x,y = 2,3; x,y = y,x; print "afer swap: ", x,y; # But there's a catch ... # there are actually 2 sets of x,y variables in the above fragment! # Python always creates new variables, so there is no state change. # This, however, does not mean that Python is pure lambda calculus. # Old Python was DYNAMICALLY scoped!! #What's even worse is that the behavior is not consistent! def g(): y = 3 def h() : return y return h y = 4 print g()(); # prints 3: older versions will print 5 # Here's how to get static (lexical scoping) in old Python: use an optional # parameter with a default value: x = 3; def g(n, x=x) : return x+n; x=4; print g(1); # prints 4 # But this won't work if you want to change x within g! ###### But there's hope for python: I = lambda x: x; K = lambda x: lambda y: x; S = lambda x: lambda y: lambda z: x(z)(y(z)); SKI = S(K)(I); # note, not same as S(K,I); print "SKI(3) is", SKI(3); # SKI beta-reduces to I, so this prints 3 print map((lambda x:x+1),[1,2,3,4]); # prints [2,3,4,5]