-2

I've searched answers on here and tried implementing them but I think that there is some tiny detail I'm missing. I have a very short python code for a program that is supposed to return the initials with periods of a persons input(for their full name). So for example, input is Atticus Leonard Beasley and output should be

A.L.B.

but instead I'm getting:

A.
L.
B.

Here's my code:

def main():

    full_name = input("Enter your first, middle, and last name: ")

    for ch in full_name:
        if ch.isupper():
            ch = ch.rstrip('\n')
            print (ch,'.', sep='')

main()
Lafexlos
  • 7,618
  • 5
  • 38
  • 53

2 Answers2

0

FYI, you can do this using split and join:

def main():

    full_name = input("Enter your first, middle, and last name: ")
    initials = []

    for name in full_name.split():
        initials.append(name[0])

    print('.'.join(initials) + '.')

main()

Or using list comprehension:

def main():

    full_name = input("Enter your first, middle, and last name: ")
    print('.'.join(name[0] for name in full_name.split())+'.')

main()
Farhan.K
  • 3,425
  • 2
  • 15
  • 26
0

I think you can do that in a easier and "more pythonic" way.

full_name = input("Enter your first, middle, and last name: ")

print(''.join([ch[0].upper() + '.' for ch in full_name.split()]))

EXPLANATIONS

Instead of doing a for loop over each letters of the name, you can use split() function to be sure to took care of every words without the extra spaces.

sentence = "hello world"

for ch in sentence.split():
    print(ch) # hello
    break

Now, you try to verify if the first letter is an uppercase, but if the user enter his name without uppercase, your function does not work. An easier solution will be to extract the first letter of the word ch[0] and automatically add an uppercase: ch[0].upper()

Maybe the one-liner solution is confusing, but most of the python developers use list comprehension over for loops when the solution is easily readable.

EDIT

One more thing, even if you are writing a simple function such as print the initials of a name, you should always write tests accordingly.

A good way to start is to use doctests because it forces you to describe what your function does. Even if you think it's a waste of times, it helps to overcome many problems when your program is getting bigger. I'd be please to help you if you want to try to write your first doctest

Kruupös
  • 5,097
  • 3
  • 27
  • 43