Using *args in Python3 to define a function that takes a variable number of arguments (or none at all)

Photo by Janko Ferlič on Unsplash
My favorite book is X.
I don't like to read.
def fav_book(book):
pass
def fav_book(book):
if book:
print(f"My favorite book is {book}.")
else:
print("I don't like to read.")
fav_book("Crime and Punishment")
My favorite book is Crime and Punishment.
fav_book()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fav_book() missing 1 required positional argument: 'book'

Using Try / Except

Next I tried accounting for this TypeError using a try statement. The idea being: “Try to run this piece of code (or in my case, this print statement), and if you get an error, print something else.” But this also left me high and dry:

def fav_book(book):
try:
print(f"My favorite book is {book}.")
except TypeError:
print("I don't like to read.")

Predefining an argument’s value in the function

I came across a bit of code online that seemed like a viable workaround. It made me realize you can set an argument equal to something within the function. Like this:

def fav_book(book="I don't like to read."):
if book != "I don't like to read.":
print(f"My favorite book is {book}.")
else:
print(book)

Solving the problem with *args

Eventually I came across the concept of *args which lets you take in more arguments than the number you defined, or zero arguments.

def fav_book(*books):
if books:
for book in books:
print(f"My favorite book is {book}.")
else:
print("I don't like to read.")
  • if statement — This loops through all the books provided when the function is called, and prints them out, like so:
fav_book("Crime and Punishment", "Fight Club", "Tao Te Ching")
My favorite book is Crime and Punishment.
My favorite book is Fight Club.
My favorite book is Tao Te Ching.
fav_book()
I don't like to read.

Coding, creativity, music, and books. Pianist & composer — @vontmer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store