Hello, welcome back to our Python course.
I want to do a little exercise with you that I found very instructive. We did this in class and it was a lot of fun. The idea is to find the initials of a name that the user has entered.
The Challenge: Creating an Initials Generator
Here’s a notebook that explains how to do that.
If I enter my name,
Andreas Matthias, I want the output to beAM.If I enter
Billy, the output should be justB.If I enter
John F. Kennedy, the output should beJFK.
So, it should pick the initials, put them into one string, and output that.
Step 1: Getting the User’s Name
And of course, the first thing we need to do is to enter a name.
name = input("Enter a name: ")
# If I enter “Andy” or whatever, nothing else happens.
# Now I have my name in the variable ‘name’.Step 2: Getting the First Initial
Now, the first of the initials is easy. If you think about it, whatever the name is, the first letter of the whole string will also be the first initial. So if I just say Billy, the first letter is B. If I say John F. Kennedy, the first letter is the J. So the first letter of the whole string must also be the first letter of the first name. It is our first initial.
This makes it easy for us to pick this out. And at the same time, we can initialize our initials variable that will keep the result with that first letter. And this is what I do next.
# ‘name[0]’ gets the first character of the string, because
# indexing starts at 0.
initials = name[0]
# Let’s print it to see what happens.
print(initials)Step 3: Looping Through the Name
And now we need to loop over the letters in the name because we don’t want to be stuck only with the first letter. We want to have all the letters. So we use a for loop. And you remember that if I use a for loop with a string, it will interpret the string as a list of characters. And this is exactly what we want. So it will go through the string character by character.
# This is just to test whether the loop works.
for letter in name:
print(letter)
# You see for “Andy”, it gives me A, N, D, and Y.
# So this works perfectly. It does exactly what we want.Step 4: Finding the Spaces
Now the next question is, how do I find the spaces in this string? Well, I have the letters one by one, and if the letter is a space, then I have found a space.


