[英]How do I ignore a string in a function that accepts multiple arguments in python?
I'm trying to answer a python programming question:我正在尝试回答一个 Python 编程问题:
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
.编写一个函数
operate_nums
,计算所有其他输入参数的乘积,如果关键字参数negate
(默认为False
)为True
则返回其负数,或者如果negate
为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.使用
isinstance
可让您检查变量的类型。 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正如@DarrylG 的评论之一所指出的,您可以使用
Number
作为参数是否是您要乘以的参数的指示符
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.