[Tutor] remarkable features of Python [types and a language comparison]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 8 Nov 2001 23:34:23 -0800 (PST)


> Perl and Sh also have dynamic typing but their typing is weak.  In
> python, try this :
> 
> print "123" + 4
> print 4 + "123"
> 
> Try it in perl
> 
> print "123" + 4 ;
> print 4 + "123" ;
> print "123" . 4 ;
> print 4 . "123" ;



[Note: this is something of a Perl language post --- please avert your
eyes if you're sensitive to this.  *grin*]


Perl's design deliberately blends strings and numbers into a concept known
as a "scalar".  Because of this blending, the language does end up having
a lot of operators.

For example, in Perl, '.' is the "concatenation" operator used to join two
strings together, and 'x' is the "multiplication" operator used to
multiply a string against a number.  As one would expect from this design,
Perl also has a set of separate comparision operators: 'lt', 'gt', and
'eq', specifically for strings.



Python, on the other hand, pushes more information on the "type" of a
value --- it figures out what we mean by "type" of the arguments.  For
example, here are three uses of the concept of "multiplication" on
different types of things:

###
## Python ##
>>> "3" * 3
'333'
>>> 3 * 3
9
>>> (3,) * 3
(3, 3, 3)
###

Python has fewer operators, but does place more emphasis on knowing about
the idea of a values's "type".  This "type" idea is something that
beginning Python programmers sometimes get stuck on, so it too has a
tradeoff.


I'm trying to figure out a way of sounding impartial about all of this,
but I must admit I'm very very biased.  *grin* I like Python's approach
better because Python's design "feels" more uniform: taking a "slice" of a
list and taking a "slice" of a string look the same in Python:

###
## Python ##
shopping_list = ['toothpaste', 'deodorant', 'mouthwash']
print shopping_list[1:]
name = 'hal'
print name[1:]
###


but "slicing" involves different operations in Perl:

###
## Perl ##
my @shopping_list = ('toothpaste', 'deodorant', 'mouthwash');
print @shopping_list[1..$#shopping_list]), "\n";
my $name = "hal";
print substr($name, 1), "\n";
###


(Note: the Perl code is not quite equivalent to the Python version, since
Perl does not define how to print arrays.  Using something like:

    print '(', join(', ', @shopping_list[1..$#shopping_list]), ')\n';

would make the outputs match more closely, but would really obscure
similarities between the code.)



Hope this helps!