Reputation: 169
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 argumentnegate
(defaultFalse
) isTrue
or just the product ifnegate
isFalse
. 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
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