PhantomDiclonius
PhantomDiclonius

Reputation: 149

Compiler not understanding my optional argument in Python

Hello I'm having issues with an exercise that is asking me to write code that contains a function, 3 dictionaries, and an optional argument.

Here is my code:

def make_album(artist_name, album_title, num_tracks):

    """Return artist and album title name."""
    CD1 = {'sonic': artist_name, 'his world': album_title}
    CD2 = {'shadow': artist_name, 'all hail shadow': album_title}
    CD3 = {'silver': artist_name, 'dream of an absolution': album_title}
    if num_tracks:
        CD = artist_name + ' ' + album_title + ' ' + num_tracks
    else:
        CD = artist_name + ' ' + album_title
    return CD.title()

disc = make_album('sonic', 'his world', '15')
print(disc)

disc = make_album('shadow', 'all hail shadow')
print(disc)

disc = make_album('silver', 'dream of an absolution')
print(disc)

Whenever I try to run my code however, my compiler states that it is missing 1 required positional argument: 'num_tracks' for my second print statement.

But this should not be an issue because of my if-else statement, unless I wrote my code incorrectly and the compiler isn't reading my if-else statement? Any feedback would be greatly appreciated, thank you for your time.

Upvotes: 1

Views: 40

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155323

You need to def the function with a default for the argument to be optional, e.g.:

# num_tracks=None means if not provided, num_tracks is set to None
def make_album(artist_name, album_title, num_tracks=None):
    ...
    if num_tracks is not None:
        CD = artist_name + ' ' + album_title + ' ' + num_tracks
    else:
        CD = artist_name + ' ' + album_title

Arguments without a default are always required.

Upvotes: 2

Related Questions