Kaya Mehta Kaya Mehta - 27 days ago 7
Python Question

Python code count letters for loop

Write a function countletter() that should have a 'for' loop that steps
through the list below and prints the name of the city and the number of
letters in the city's name. You may use the len() function.

citylist = ["Kentucky","New York","LA", "Toronto",
"Boston","District of Columbia"]


I am using Python 3.5 in Spyder. I am having trouble extracting the letters from the list and then having them print out within the for loop.

What I have:

def countletter(citylist):
city = len(citylist)
ct = 0
for i in citylist:
city = (ne[i])


and then I get stuck. I fear this may be entirely wrong. I am also struggling on how to print this.

The output should be:

Kentucky has 8 letters.

New York has 12 letters.

LA has 2 letters.

Toronto has 7 letters.

Boston has 6 letters.

District of Columbia has 20 letters.

Thank you for the help!

Answer

You don't need to use indices. Just iterate citylist; for loop will yield each city.

def countletter(citylist):
    for city in citylist:
        n = len(city)
        print(city, 'has', n, 'letters.')


citylist = ["Kentucky","New York","LA", "Toronto", "Boston","District of Columbia"]
countletter(citylist)

output:

Kentucky has 8 letters.
New York has 8 letters.
LA has 2 letters.
Toronto has 7 letters.
Boston has 6 letters.
District of Columbia has 20 letters.