"OKB (not okblacke)" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Primoz Skale wrote: > >> OK, everything allright till so fair. But! :) Now define third >> function as: >> >> def f(*a): >> print a[0] >> >> In this case, function only prints first argument in the tuple: >> >>>>f(1,2,3) >> 1 >>>>f(3) >> 3 >>>>f() #no arguments passed >> Traceback (most recent call last): >> File "<pyshell#425>", line 1, in <module> >> f() #no arguments passed >> File "<pyshell#422>", line 2, in f >> print a[0] >> IndexError: tuple index out of range >> >> Then I tried to define the function as: >> >> def f(*a=(0,)): >> print a[0] #this should come next, but we get error msg instead, >> saying >> >> SyntaxError: invalid syntax >> >> but it does not work this way. Now my 'newbie' question: Why not? >> :) I wanted to write function in this way, because then we can call >> function without any arguments, and it would still print 0 (in this >> case). >> >> What I wanted was something like this: >> >> def f(*a=(0,)): >> print a[0] >> >>>>f(1,2) >> 1 >>>>f() #no args passed 0 > > When you use the *a syntax, you're saying that you want a to > contain a tuple of all the arguments. When you try *a=(0,), you seem to > be saying that you want a to hold all the arguments, or, if there are > none, you want to pretend that it was called with one argument, namely > 0. > > Well, if you want to ensure that there is at least one argument, > and print that first one, and make it zero if it's not supplied, why are > you using the *a syntax? You're clearly treating that first argument > distinctly, since you want to apply a default value to it but not to any > others. Just do this: > > def f(a, *b): > print a
Thanks! I never thought of that.... :) P. > > -- > --OKB (not okblacke) > Brendan Barnwell > "Do not follow where the path may lead. Go, instead, where there is > no path, and leave a trail." > --author unknown -- http://mail.python.org/mailman/listinfo/python-list