function call - default value & collecting arguments
Primoz Skale
primoz.skale.lists at gmail.com
Wed Apr 2 15:03:36 EDT 2008
Hello!
I am fairly new to Python, so I apologise if this is a 'newbie' question.
First define a simple function:
def f(a=0):
print a
>> f(1)
1
>>f()
0
Argument a in function f() is set at default value of 0, if it is not passed
to the function at the function call. I get this! :)
I also understand (fairly) how to collect arguments. For example, let's
define another function:
def f(*a):
print a
>>f(1)
(1,)
>>f(1,2)
(1,2)
>>f()
()
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
but this of course does not work. Again, why not?
Thank you for your comments.
Primoz
More information about the Python-list
mailing list