Functions

Functions with optional parameters

In Python, we can create functions with optional parameters by providing default values for the parameters in the function definition.

If a value for the parameter is not required inside the function, we typically set the default value to None (which is equivalent to NULL in some programming languages, such as PHP).

When the function is called, if an argument is passed, the function will use it. If no argument is passed, the parameter will default to None.

In the following example, the first time we call the function, we pass it an argument that is a variable containing a name.

The second time we call the function, we do not pass it an argument, and so the parameter defaults to None (and no error occurs).

Run the following code
# Define the function.
# This function has one parameter, a name, but it is not required.
def greet_person1(name=None):
greeting = 'hello ' + name if name is not None else 'hello'
return greeting

# Set three variables.
name1 = 'Jess'
name2 = 'Tracy'
name3 = 'Haru'

# Call the function.
print('Using greet_person1() with a string value contained in a variable passed as an argument, and with no name passed in (None is permitted)')

print(greet_person1(name1)) # When the function is passed an argument, it works as expected.

print('')

print(greet_person1()) # If no argument is passed to the function, it will NOT cause an error. Just 'hello' will be output.

print('')

In the previous example, the default value for the parameter was None.

If you call the function without passing it an argument, it will use the default value that was specified in the function definition.

# Define the function.
# This function has one parameter, name, but passing an argument to the function is optional - the default value 'world!' will be used if you do not pass an argument.
def greet_person2(name='world!'):
greeting = 'hello ' + name
return greeting

# Set three variables.
name1 = 'Jess'
name2 = 'Tracy'
name3 = 'Haru'

# Call the function.
print('Using greet_person2() with one name passed as an argument, and using the default parameter')

print(greet_person2(name1)) # When the function is passed an argument, it works as expected.

print('')

print(greet_person2()) # If no argument is passed to the function, it will NOT cause an error. 'hello world!' will be output, because the default value for name was set to 'world!'.

print('')