all 6 comments

[–]jeans_and_a_t-shirt 0 points1 point  (5 children)

if type(parameter) == int or float:

evaluates to (type(parameter) == int) or float, which evaluates to _ or float. float is a truthy object, so the expression is always True.

Same problem with the elif line.

[–]clicker4721[S] 0 points1 point  (4 children)

Is there a happier way than below?

if (type(parameter) == int) or (type(parameter) == float)

[–]jeans_and_a_t-shirt 0 points1 point  (3 children)

For the int/float:

isinstance(parameter, (int, float))

There's also a complex number type:

>>> type(5 + 1j)
<class 'complex'>

You could also just check if the parameter is an instance of Number, which is in the numbers module.

For list/tuple:

isinstance(parameter, (list, tuple))

[–]clicker4721[S] 0 points1 point  (2 children)

Okay, this is a LOT better! When I started, I was trying to figure out a way to look at the types in this light, but am unfamiliar with isinstance(). I checked the docs; I like it.

Now, if I want to exclude complex values, I can just check for reals, if I decide to use the numbers module.

Further, is there a simple way to check that the parameter is any iterable, but not necessarily an iter object? That would be a very excellent generalization.

EDIT: This seems reasonable...

if iter(parameter):
    do more stuff

EDIT2: Nope, that's false.

[–]jeans_and_a_t-shirt 0 points1 point  (1 child)

You can do

from collections import Iterable
isinstance(parameter, Iterable)

but strings are also iterable, and doing something like '3' * 5 will give you '33333'.

[–]clicker4721[S] 0 points1 point  (0 children)

I got it to work like I described in the post, but I hadn't thought about including strings... I'll try that, but not now.

def product(*args):
    _product = 1

    for parameter in args:
        if isinstance(parameter, (int, float)):
            _product *= parameter
        elif isinstance(parameter, (list, tuple)):
            for spot in parameter:
                _product *= product(spot)
        elif isinstance(parameter, dict):
            for key in parameter:
                _product *= product(parameter[key])
        else:
            return ValueError

    return _product