1

I'm trying to answer a python programming question:

Write a function operate_nums that computes the product of all other input arguments and returns its negative if the keyword argument negate (default False) is True or just the product if negate is False. The function should ignore non-numeric arguments.

So far I have the following code:

def operate_nums(*args):
     product = 1
     negate = True

     for i in args:
         product = product * i

     if negate == True:
         return product * -1
     return product

If I input a set of numbers and strings in my argument, how will code it so that my code ignores the strings?

pancakes
  • 159
  • 1
  • 2
  • 14
  • 1
    FWIW, `negate` is supposed to be a *keyword argument*, so: `def operate_nums(*args, negate = False): ...` – deceze Mar 18 '20 at 10:11
  • 1
    To ignore non-numeric values in your for loop you can use isinstance(i, Number) to check if i is a number before attempting to multiply as explained [What is the most pythonic way to check if an object is a number?](https://stackoverflow.com/questions/3441358/what-is-the-most-pythonic-way-to-check-if-an-object-is-a-number). – DarrylG Mar 18 '20 at 10:16

1 Answers1

3

Use isinstance that lets you check the type of your variable. As pointed in one of the comments by @DarrylG, you can use Number as an indicator whether an argument is the one you want to multiply by

from numbers import Number

def operate_nums(*args, negate=False):
    product = 1

    for arg in args:
        if isinstance(arg, Number): # check if the argument is numeric
            product = product * arg

    if negate == True:
            return product * -1

    return product
balkon16
  • 1,338
  • 4
  • 20
  • 40
  • thank you so much!! i didn't know that you can pass booleans in function arguments – pancakes Mar 18 '20 at 10:22
  • 1
    This only ignores strings. You could use `if isinstance(arg, Number): product = product * arg` where Number is defined by `from numbers import Number`. Then any type of non-numeric (such as None, [], {}, etc.) is ignroed. – DarrylG Mar 18 '20 at 10:31