1

Is it posible to have an optional veriable in a funtion?

Such as this:

>>>def Say(msg, (optional)):
>>>    print msg
>>>    print optional
>>>    
>>>Say('hi', 'option')
hi
option
>>>Say('not')
not

If so How?

4
Contributors
4
Replies
56
Views
2 Years
Discussion Span
Last Post by DragonMastur
Featured Replies
  • Yes is called default argument. def say(msg, arg='something'): print 'first argument <{}> default argument <{}>'.format(msg, arg) >>> say('hello') first argument <hello> default argument <something> >>> say('hello', 'world') first argument <hello> default argument <world> Many arguments. def foo(*arg): return sum(arg) >>> foo(1,2,3,4,5,6,7,8,9,10) 55 Keyword arguments. def bar(**kwargs): for key, value in … Read More

3

Yes is called default argument.

def say(msg, arg='something'):
    print 'first argument <{}> default argument <{}>'.format(msg, arg)

>>> say('hello')
first argument <hello> default argument <something>
>>> say('hello', 'world')
first argument <hello> default argument <world>

Many arguments.

def foo(*arg):
    return sum(arg)

>>> foo(1,2,3,4,5,6,7,8,9,10)
55  

Keyword arguments.

def bar(**kwargs):
    for key, value in kwargs.items():
        print '{}: {}'.format(key, value)

>>> bar(first_name='Clark kent', last_name='Superman')
first_name: Clark kent
last_name: Superman
0

You could do this ...

def say(msg, optional=""):
   print(msg)
   if optional:
       print(optional)

say('hi', 'option')

'''
hi
option
'''

print('-'*12)

say('not')

'''
not
'''

But this is far simpler ...

def say(*args):
    for arg in args:
        print(arg)


say('hi', 'option')

'''
hi
option
'''

print('-'*12)

say('not')

'''
not
'''
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.