Optional Parameters
Optional Parameters#
Sometimes when dealing with functions, we want to give the caller the flexibility of specifying a parameter, but we can offer a sensible default. For instance, let’s say we are writing a hello world function and we want to be able to allow the function to print the string in english or spanish. We can add a parameter to the function which requires the caller to specify which language they would like to use. But we expect most often that our user will prefer english. We can save them the trouble of specifying this, by defining a default value for language. The caller then can be explicit about which language or just use our default.
# define a function that prints hello world in english or spanish depending on the input
def hello_world(language='english'):
if language == 'english':
print('Hello World')
elif language == 'spanish':
print('Hola Mundo')
else:
print('I don\'t know that language')
# call the function
hello_world() # If we don't specify, it will assuming english
# call the function with a different language
hello_world('spanish')
Hello World
Hola Mundo
Sometimes functions take a number of optional parameters, so it’s best to be explicit about what you mean rather than calling the function and counting on the order of the parameters. For instance,
def my_func(a, b=0, c='all'):
print(a)
print(b)
print(c)
In this example, `a` is required, but `b` and `c` are optional. This means you can specify values for these parameters and if you don't the defaults will be `0` and `"all"`.
You can try this in the next cell. Try a few of your own combinations until you get the hang of it.
def my_func(a, b=0, c='all'):
print("a=", a)
print("b=", b)
print("c=", c)
# Here we depend on the order of the arguments (not a great idea, better to be explicit)
my_func(1, 2, 3)
a= 1
b= 2
c= 3
a= 1
b= 2
c= all
a= 1
b= 0
c= 3
# Here we can specify the arguments by name, but only the ones we want to change
my_func(1, b=2)
print('---')
my_func(1, c=3)
# And we can put the optional parameters in any order, so long as we specify them by name
print('---')
my_func(1, c=3, b=2)
a= 1
b= 2
c= all
---
a= 1
b= 0
c= 3