[Tutor] How to make def where arguments are either stated when called or entered via raw_input

Brian van den Broek brian.van.den.broek at gmail.com
Thu Feb 9 12:55:03 CET 2012


On 9 Feb 2012 13:34, "David Craig" <dcdavemail at gmail.com> wrote:
>
> Hi,
> 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??
> Thanks
> D
>
>
> def NoiseCorr(file1,file2,500,0.25,0.35):
>
>
#######################################################################################
> ### Check number of arguments
>    ??????????????????
>
>
#######################################################################################
> ### User inputs.
>    if numArgs == 0:
>       file1 = raw_input('Path to Station 1: ')
>       file2 = raw_input('Path to Station 2: ')
>       shift_length = raw_input('Length of Correlation: ')
>       freqMin = raw_input('Min. Frequency: ')
>       freqMax = raw_input('Max. Frequency: ')

Hi David,

>From your description, it doesn't sound as though you do need the number of
arguments. Are you familiar with keyword args and default values?

I would do it like so:

def myfunc(x=None):
    if x is None:
        x=raw_input(a_prompt)

expanding the arg list as needed. This also allows for callers to specify
only some of the values.

HTH,

Brian vdB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120209/269619f5/attachment.html>


More information about the Tutor mailing list