# [Tutor] recursive problem

Roelof Wobben rwobben at hotmail.com
Sat Sep 11 20:09:20 CEST 2010

```

----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sun, 12 Sep 2010 04:03:43 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
>
>> But why is type checking then wrong.
>> Lets says I want a module who must work on strings, tuple and lists.
>
> It's not *always* wrong, but let me ask you... why do you want to
> *limit* the function to work on ONLY strings, tuples and lists?
>
> The Python philosophy is "duck typing" -- if it walks like a duck, and
> swims like a duck, it is close enough to a duck that we don't care that
> it's not actually a duck, but a goose.
>
> Here's an example:
>
>
> def f1(x):
> if type(x) is int or type(x) is float:
> print("x + 1 = %s" % (x+1))
> else:
> print("x is not a number")
>
>
> def f2(x):
> try:
> print("x + 1 = %s" % (x+1))
> except (ValueError, TypeError):
> print("x is not a number")
>
>>>> f1(3)
> x + 1 = 4
>>>> from decimal import Decimal
>>>> f1(Decimal(3))
> x is not a number
>>>> f2(Decimal(3))
> x + 1 = 4
>
> Function f1 makes the assumption that only ints and floats can be added,
> and so it gives the wrong results with Decimal numbers. But function f2
> uses "duck typing" -- it doesn't care what sort of number x is, only
> that it can be added.
>
>
>
>> Can I then use EAFP ?
>>
>> Without type checking I never know which one is used now.
>
>
> Going back to type-checking... sometimes you can't avoid it. Sometimes
> you use it because it is easier, and you don't care enough to write
> more complicated code. Sometimes you really do care what the type is:
>
>>>> "abc"[2.0]
> Traceback (most recent call last):
> File "", line 1, in
> TypeError: string indices must be integers
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello Steven,

Because I follow this book "Thinking like a computer scientist" and I have only read the chapters about strings. lists and tuples.

Roelof

```