P
Primoz Skale
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
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
()
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:
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]
0
but this of course does not work. Again, why not?
Thank you for your comments.
Primoz
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
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
()
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:
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]
0
but this of course does not work. Again, why not?
Thank you for your comments.
Primoz