optional argument - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

optional argument

justin8justin8 Posts: 4Member
Hello,

I want to create a function and I want to use an optional argument, so whether this argument is used or not when calling the function, the function still will be called. Does anybody know how to do that in Python?


Comments

  • infidelinfidel Posts: 2,900Member
    : Hello,
    :
    : I want to create a function and I want to use an optional argument, so whether this argument is used or not when calling the function, the function still will be called. Does anybody know how to do that in Python?

    There are a couple of ways. If you want it to have a default value, you can do this:

    [code]
    def myfunc(foo, bar = 2):
    print foo * bar
    [/code]

    You can now call it a couple of ways. If you don't pass a value for bar, it defaults to 2:

    [code]
    >>> myfunc(3)
    6
    >>> myfunc(3,4)
    12
    >>> myfunc('foobar')
    foobarfoobar
    >>> myfunc('foobar',5)
    foobarfoobarfoobarfoobarfoobar
    [/code]

    You can also accept any number of optional arguments using a special tuple syntax:

    [code]
    def myfunc2(foo, *args):
    print foo, args
    [/code]

    Now you can call your function with as many additional arguments as you like and they call get packed into a tuple named args (or whatever else you name it, doesn't have to be "args", though that is common).

    [code]
    >>> myfunc2(1)
    1 ()
    >>> myfunc2('foobar', 'geewhiz', 'yeehaw')
    foobar ('geewhiz', 'yeehaw')
    [/code]

    You can do something similar with optional named arguments, perhaps if you want to send certain flags or keywords to your function. These get placed into a dictionary.

    [code]
    def myfunc3(foo, **kwargs): #kwargs stands for "keyword args"
    print foo, kwargs
    [/code]

    [code]
    >>> myfunc3('one fish two fish red fish blue fish')
    one fish two fish red fish blue fish {}
    >>> myfunc3('my flags', red = True, green = False, blue = 3)
    my flags {'blue': 3, 'green': False, 'red': True}
    [/code]




    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

    [code]
    $ select * from users where clue > 0
    no rows returned
    [/code]

Sign In or Register to comment.