Member-only story
Using *args in Python3 to define a function that takes a variable number of arguments (or none at all)
Mini-learns with Python
The other day I ran into a problem asking me to provide one kind of output if an argument was given, and another if no argument was given.
For example — given a book, return the message:
My favorite book is X.
Where X is the given book.
However, if the book is missing, return the string:
I don't like to read.
The exercise came with the following function to manipulate:
def fav_book(book):
pass
I wrongly assumed I could only change text in the function suite (where pass
was), instead of the argument itself. As a result, the first function I came up with was something like this:
def fav_book(book):
if book:
print(f"My favorite book is {book}.")
else:
print("I don't like to read.")
Essentially saying, “If the book exists when the function is called, tell us your favorite book. Otherwise (else) tell us you don’t like to read.”
This worked when passing the function an argument:
fav_book("Crime and…