1

I'm new to 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. While on other hand if if condition is false then that portion of code is executed and else is skipped.

Can you explain why the if statement is executed on False condition ?

3 Answers 3

7

No, args == 3 is not True. You probably meant len(args) == 3.

Sign up to request clarification or add additional context in comments.

3 Comments

@savruk But only very maybe.
totally agree there, as I didn't read the question well. My sorry
@cdarke What insight should I get from this? The error is obvious.
4

I think you must be doing len(args)==3 instead of args==3:

if len(args)==3:

the condition args==3 is never going to be true as args becomes a tuple inside the function.

so even if you pass myfunc(3), then also you'll be matching (3,)==3, which is False.

1 Comment

ahhhhh thank you so much.After printing args and len(args), now I get the idea why. :)
0

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.

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.

1 Comment

how's your answer different from the other two answers?and args is not a list of tuple , it's just a tuple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.