[Tutor] How to make def where arguments are either stated when called or entered via raw_input
Peter Otten
__peter__ at web.de
Thu Feb 9 12:51:01 CET 2012
David Craig wrote:
> I'm trying to write a function that will either take arguments when the
> function is called, such as myFunc(x,y,z) or if the user does not enter
> any arguments, myFunc() the raw_input function will ask for them. But I
> dont know how to check how many arguments have been entered. My code is
> below. Anyone know how??
You either can use a star argument that causes the function to accept an
arbitrary number of arguments which are put into a tuple
>>> def f(*args):
... if not args:
... x = raw_input("x? ")
... y = raw_input("y? ")
... z = raw_input("z? ")
... else:
... x, y, z = args
... print "x=%r, y=%r, z=%r" % (x, y, z)
...
>>> f()
x? alpha
y? beta
z? gamma
x='alpha', y='beta', z='gamma'
>>> f(1, 2, 3)
x=1, y=2, z=3
>>> f(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in f
ValueError: need more than 1 value to unpack
or provide default values that cannot occur as normal input:
>>> def f(x=None, y=None, z=None):
... if x is None: x = raw_input("x? ")
... if y is None: y = raw_input("y? ")
... if z is None: z = raw_input("z? ")
... print "x=%r, y=%r, z=%r" % (x, y, z)
...
>>> f()
x? one
y? two
z? three
x='one', y='two', z='three'
>>> f("ONE", z="THREE")
y? two
x='ONE', y='two', z='THREE'
> def NoiseCorr(file1,file2,500,0.25,0.35):
That's a syntax error. Try to be more careful about the code you are posting
here.
More information about the Tutor
mailing list