Here's a sample Python program which prints out the first 10 elements of the Fibonacci series:
a, b = 0, 1 for i in range ( 0, 10 ): print b, a, b = b, a+b
Note how more than one variable can be assigned values in a single statement. It doesn't sound like much, except that it's a side-effect of something much bigger (tuple packing and unpacking). Also, in Python, indentation is the only way to nest blocks. You can't have confusing indentation in Python. This is WYSIWYG as applied to programming :-).
Here's another Python program which prints all prime numbers in the range 1 to 100:
primes = [2] for i in range ( 3, 101, 2 ): for j in primes: if ( i % j ) == 0: break else: primes.append( i ) print primes
Set operations are easy as pie - primes.append(), primes.insert(), primes.remove() and other very object-oriented constructs. Also, note something curious in the example above. The else is indented below the for, not below the if. What gives?
It refers to the case where the loop was exited normally and not through the break statement. In other languages, we might have needed a boolean called "found" or something. In Python, it's much cleaner.
Like it? Imagine a shell based on Python. I've let my imagination run riot in the example below, where I compile all C files containing a certain variable, and then check which ones didn't compile:
pysh> ignore = /dev/null # This could have been defined in the .profile pysh> ls a.out temp.c temp1.c new.c latest.c pysh> cfiles = *.c pysh> compilefiles = [] pysh> for i in cfiles: ... if grep( "RequiredVar", i ).len() > 0: ... cc -c i 2>ignore ... compilefiles.append( i ) ... pysh> objfiles = *.o pysh> for i in compilefiles: ... if ( i - '.c' + '.o' ) not in objfiles: ... print i, 'could not be compiled' ... pysh>
Bringing the power of lists, tuples and associative arrays (dictionaries) to the shell will be really exciting. Why, we could even have a "Perl Shell", for those who want to do lots of things in two lines of code ;-).
What do you think of this, Guido and Larry?
(Python is Guido van Rossum's brainchild, and Perl is Larry Wall's)
Mail me at gcp@emirates.net.ae or at g.c.prasad@usa.net . I used to have a Hotmail account, but gave it up after it was taken over by the Evil Empire :-(.
Hits so far: