Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22880

The Python Coding Blog: Optional Arguments With Default Values in Python Functions [Intermediate Python Functions Series #3]

$
0
0

We continue our journey through Python functions by looking at optional arguments and default values.

In this article, you’ll see how you can define a function with an optional argument. A default value is used if the argument is not included in the function call.

Overview Of The Intermediate Python Functions Series

Here’s an overview of the seven articles in this series:

  1. Introduction to the series: Do you know all your functions terminology well?
  2. Choosing whether to use positional or keyword arguments when calling a function
  3. [This article] Using optional arguments by including default values when defining a function
  4. Using variable numbers of positional and keyword arguments: *args and **kwargs
  5. Using positional-only arguments and keyword-only arguments: the “rogue” forward slash / or asterisk * in function signatures
  6. Type hinting in functions
  7. Best practices when defining and using functions

Using Optional Arguments With Default Values

Let’s build on the same function used in the previous articles in this series:

def greet_person(person, number):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

# 1.
greet_person("Sara", 5)

# 2.
greet_person("Kevin")

One of these calls raises an error. Can you guess which one?

Let’s look at the first one. The first call works fine. It uses two positional arguments:

def greet_person(person, number):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

# 1.
greet_person("Sara", 5)

The output is:

Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?

However, the second call raises an error:

def greet_person(person, number):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

# 2.
greet_person("Kevin")

The output is:

Traceback (most recent call last):
  File "...", line 6, in <module>
    greet_person("Kevin")
TypeError: greet_person() missing 1 required positional argument: 'number'

This is where knowing the terms we introduced in the previous articles helps. The error says:

greet_person() missing 1 required positional argument: 'number'

You said you’ll provide two arguments when you defined the function but only provided one. Python can’t live with that, understandably. There’s missing information. Therefore, it cannot execute the function.

However, you can define the function so that the parameter number has a default value. This makes the second positional argument an optional argument:

def greet_person(person, number=2):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

# 1.
greet_person("Sara", 5)

# 2.
greet_person("Kevin")

The output is now fine for both calls:

Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Kevin! How are you doing today?
Hello Kevin! How are you doing today?

In the function signature, you added a default value using an equals sign right after the parameter name number. This means that if you don’t provide an argument for this parameter, the default value of 2 will be used. If you do provide a second positional argument, that argument will be used, as in the call:

greet_person("Sara", 5)

Parameters With Default Values Must Come After Ones Without

Now, for some rules you cannot break. When you define the function, you cannot place parameters with default values before parameters which don’t have defaults:

def greet_person(number=2, person):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

When you run this, you get an error:

File "...", line 1
    def greet_person(number=2, person):
                               ^^^^^^
SyntaxError: non-default argument follows default argument

Note that in this case, the error is raised when defining the function and not when calling it. The error message helpfully states what the problem is:

SyntaxError: non-default argument follows default argument

Including More Optional Arguments

You can have both parameters with default values if you prefer. This means you can call the function with no arguments, one argument, or both arguments:

def greet_person(person="there", number=2):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

# 1.
greet_person("Sara", 5)

# 2.
greet_person("Kevin")

# 3.
greet_person() 

Here’s the output showing all three function calls worked fine:

Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Sara! How are you doing today?
Hello Kevin! How are you doing today?
Hello Kevin! How are you doing today?
Hello there! How are you doing today?
Hello there! How are you doing today?

And since both arguments are optional, you can even call the function using just the second argument but not the first. However, to do this you’ll need to use named arguments and not positional ones:

def greet_person(person="there", number=2):
    for greeting in range(number):
        print(f"Hello {person}! How are you doing today?")

greet_person(number=5)

Output:

Hello there! How are you doing today?
Hello there! How are you doing today?
Hello there! How are you doing today?
Hello there! How are you doing today?
Hello there! How are you doing today?

Many Ways Of Referring To The Same Thing

A note on terminology. You’ll find several ways people refer to this concept:

  • optional argument: you have a choice on whether to put in a value as an argument or not when calling the function
  • parameter with default value: the parameter in the function definition has a default value
  • default argument: the function definition already has an argument ready to be used as a default if needed
  • default parameter or optional parameter: these are also used, although they’re technically incorrect. The parameter is always there. It’s the argument which is optional and has a default value

But my advice is not to worry too much about these technicalities initially!

Final Words

A function with an optional parameter gives more flexibility to the user calling the function. It makes a function easier to use as it can be used with just the required arguments while still allowing the user to include the optional argument.

In summary:

  • When you define a function you can add a default value to one or more parameters in the function signature
  • You achieve this by adding an equals after the parameter name followed by the default value
  • When you call the function, the corresponding argument is optional. If the argument is not present in the function call, the default value is used

Next Article:<Link will be posted here when the next article in the series is posted>

Further Reading


Get the latest blog updates

No spam promise. You’ll get an email when a new blog post is published


The post Optional Arguments With Default Values in Python Functions [Intermediate Python Functions Series #3] appeared first on The Python Coding Book.


Viewing all articles
Browse latest Browse all 22880

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>