[英]Passing multiple variables in function with *args variable
I'm new to python. 我是python的新手。 Look at this script please:
请看以下脚本:
def myfunc(*args):
print len(args)
if args == 3:
for arg in args:
print arg
else:
print "exit"
a, b, c = 1, 2, 3
myfunc(a, b, c)
As you can see, the number of arguments passing to function is three. 如您所见,传递给函数的参数数量为三个。 Now condition
args==3
is True
but the else
portion is executed. 现在,条件
args==3
为True
但执行else
部分。 While on other hand if if
condition is false then that portion of code is executed and else
is skipped. 另一方面,
if
条件为假,则执行该部分代码, else
跳过该部分。
Can you explain why the if
statement is executed on False condition ? 您能解释为什么
if
语句在False条件下执行吗?
No, args == 3
is not True
. 不,
args == 3
不是 True
。 You probably meant len(args) == 3
. 您可能是
len(args) == 3
。
I think you must be doing len(args)==3
instead of args==3
: 我认为您必须在做
len(args)==3
而不是args==3
:
if len(args)==3:
the condition args==3
is never going to be true as args
becomes a tuple inside the function. 条件
args==3
永远不会成立,因为args
成为函数内部的元组。
so even if you pass myfunc(3)
, then also you'll be matching (3,)==3
, which is False
. 因此,即使您通过
myfunc(3)
,也将匹配(3,)==3
,即False
。
You have to apply len(args) == 3
instead of args == 3
because if you use args
then it is a list of tupple and if you check against it must go to else
condition. 您必须应用
len(args) == 3
而不是args == 3
因为如果使用args
则它是一个tupple列表,并且如果检查它必须转到else
条件。
def myfunc(*args):
if len(args) == 3:
for arg in args:
print arg
else:
print "exit"
a, b, c = 1, 2, 3
myfunc(a, b, c)
This code give you an expected result. 此代码为您提供了预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.