Assign default value to function parameters

Adding default value to parameters

For named parameter we can provide default value. If no value is provided during the method calling the default values are used.


def hello(greeting='Hello', name='world'): 
    print '%s, %s!' % (greeting, name) 
# ww w  .j  a va  2  s . c o  m
hello() 
hello('Greetings') 
hello('Greetings', 'universe') 

# To supply only the name, leaving  the default value for the greeting.
hello(name='Gumby') 


def fun(name, location, year=2006):
    print "%s/%s/%d" % (name, location, year)

fun("Teag", "San Diego")

def fun(name, location, year=2006):
    print "%s/%s/%d" % (name, location, year)

fun(location="L.A.", year=2004, name="Caleb" )

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules