[Tutor] Please critique my temperature_conversion.py

Magnus Lyckå magnus at thinkware.se
Mon Jul 12 12:12:47 CEST 2004

At 19:40 2004-07-11 -0400, Bill Mill wrote:
>note that if you leave a number out of a string slicing operation, it
>is assumed to be zero.

Not quite. A left out value is equvalent with None. See below:

 >>> l = list("abcdefgh")
 >>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
 >>> l[:2]
['a', 'b']
 >>> l[0:2]
['a', 'b']
 >>> l[None:2]

So far it's all the same...but not for the other places
in the slice.

['a', 'b']
 >>> l[2:]
['c', 'd', 'e', 'f', 'g', 'h']
 >>> l[2:0]
 >>> l[2:None]
['c', 'd', 'e', 'f', 'g', 'h']

 >>> l[:2:]
['a', 'b']
 >>> l[:2:0]

Traceback (most recent call last):
   File "<pyshell#8>", line 1, in -toplevel-
ValueError: slice step cannot be zero
 >>> l[:2:None]
['a', 'b']

As you see, 0 and None differ for the second and third number
in the slice.

The third digit in the slice is for stepping:

 >>> l[2:None:2]
['c', 'e', 'g']
 >>> l[2::2]
['c', 'e', 'g']

So, if you don't hardcode you slice values, but use something
like "l[start:stop:step]" you need to use "None", not "0", for
default values. You could use...
   import sys
...as default values instead of None, but I think None is simpler...

Magnus Lycka (It's really Lyck&aring;), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 

More information about the Tutor mailing list