简体   繁体   English

使用* args变量在函数中传递多个变量

[英]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==3True但执行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.

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