jason jason - 9 months ago 49
Python Question

Trying to create python program, but simplified with def

I'm trying to create a program without importing anything. The program lets the user input a passage, then prints how many A's there are in the message, how many B's, etc.
So it works...it's just VERY long. I'm new to coding, and I know that there is a way to simplify the code below with def but I'm not really sure how. Can anyone help?

Answer Source

You need no methods, but you can definately cut it short:

  • String can be used as an array of characters.
  • You can use the index method to determine what is the position of the letter in the alphabet.
  • You can iterate a zipped list of pairs from the alphabet and the counter list, to produce the output.
  • Use if letter in alphabet as a guard to ensure the letter is valid for the alphabet, instead of hard coding the alphabet. That way you can even expand your alphabet. (Note that the counter is set to the length of the alphabet).

Here is a suggestion:

message = input('what is your message? ').upper()
counter = [0] * len(alphabet)

for letter in message:
    if letter in alphabet:
        counter[alphabet.index(letter)] += 1

for letter, count in zip(alphabet, counter):
    print(letter, ':', count)