Function That Returns Capitalized Initials of Name
<p>I created a Python function that takes an argument, fullname, gets fullname's initials and prints them out capitalized. But there's a problem with my code - it only works with two names. It breaks if the fullname has a middle name, i.e. Daniel Day Lewis. </p>

<p>Here is what I tried: </p>

<pre><code>def get_initials(fullname):
    xs = (fullname)
    name_list = xs.split()

    print(name_list)

#Given a person's name, return the person's initials (uppercase)

    first = name_list[0][0]
    second = name_list[1][0]

    return(first.upper() + second.upper())

answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer) 
</code></pre>

<p>Obviously this attempt only includes two variables, one for the first name and one for the second name. If I add a third variable, like this: </p>

<pre><code>def get_initials(fullname):
    xs = (fullname)
    name_list = xs.split()

    print(name_list)

#Given a person's name, return the person's initials (uppercase)

    first = name_list[0][0]
    second = name_list[1][0]
    third = name_list[2][0]
    return(first.upper() + second.upper() + third.upper())

answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer) 
</code></pre>

<p>I get:</p>

<pre><code>IndexError: list index out of range on line 10
</code></pre>

<p>(which is the line)</p>

<pre><code>third = name_list[2][0]
</code></pre>

<p>Of course this function does work if I change fullname to "Ozzie Smith Jr". But my function has to work regardless of whether there are 1, 2, 3, or 4 names in fullname. I need to say something like:</p>

<pre><code>def get_initials(fullname):
    xs = (fullname)
    name_list = xs.split()

    print(name_list)

#Given a person's name, return the person's initials (uppercase)

    first = name_list[0][0]

    #if fullname has a second name: 
    second = name_list[1][0]

    #if fullname has a third name: 
    third = name_list[2][0]

    #if fullname has one name:
    return(first.upper())

    #if fullname has two names:
    return(first.upper() + second.upper())

    #if fullname has three names:
    return(first.upper() + second.upper() + third.upper())

    #if fullname has three names:
    return(first.upper() + second.upper() + third.upper + fourth.upper())

answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
</code></pre>

<p>How do I say "if fullname has a second name or third name or fourth name, return the uppercase initial" in Python? Or am I on the right track? Thank you. </p>