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

Steven D'Aprano steve at pearwood.info
Thu Feb 9 12:41:14 CET 2012


David Craig 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??


Does this suit your requirements?


def myFunc(x=None, y=None, z=None):
     if x is None:
         x = float( raw_input("Please enter a value for x: ") )
     if y is None:
         y = float( raw_input("Please enter a value for y: ") )
     if z is None:
         z = float( raw_input("Please enter a value for z: ") )
     # do something with x, y, z


I've assumed that you want float arguments. If not, change the calls to float 
to something else, or to leave them as strings, remove them altogether.



-- 
Steven



More information about the Tutor mailing list