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?

2
  • 1
    FWIW, negate is supposed to be a keyword argument, so: def operate_nums(*args, negate = False): ... Commented Mar 18, 2020 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?. Commented Mar 18, 2020 at 10:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much!! i didn't know that you can pass booleans in function arguments
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.