简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM