pancakes
pancakes

Reputation: 169

How do I ignore a string in a function that accepts multiple arguments in python?

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?

Upvotes: 1

Views: 369

Answers (1)

balkon16
balkon16

Reputation: 1438

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

Upvotes: 3

Related Questions