Home > Back-end >  Enter names, display them as a list and print only the names that start with letter A from list
Enter names, display them as a list and print only the names that start with letter A from list

Time:05-07

def make_list(number):
    names=[]
    for item in range (number):
        names.append(input("Enter your name with a capital letter."))
    print(names)
    
number=int(input("How many names need to be entered?"))
names=make_list(number)
for i in names:
    if names[i]=="A":
        print("Name", i, "Starts with A")

Getting an error: Nonetype object not iterable.Any help please?

CodePudding user response:

  1. Your method doesn't return the list, so default is None you need to give it back from it

    def make_list(number):
        names = []
        for item in range(number):
            names.append(input("Enter your name with a capital letter."))
        return names
    
  2. When you iterate over a list, the element is an item of the list, not an indice

    for name in names:
        # name is a value, a string
    
  3. Use str.startswith

    if name.startswith("A")
    

names = make_list(number)
for name in names:
    if name.startswith("A"):
        print("Name", name, "Starts with A")

CodePudding user response:

You just doesn't return anything from make_list function and names variable in global scope is empty. Add return statement like

def make_list(number):
    names=[]
    for item in range (number):
        names.append(input("Enter your name with a capital letter."))
    print(names)
    return names

CodePudding user response:

As the other answers have mentioned, you were missing a return for make_list. Here is another solution. You needed to iterate through names and check if the first character of name, name[0], is equal to A.

def make_list(number):
    names=[]
    for item in range (number):
        names.append(input("Enter your name with a capital letter."))
    return names
    
number=int(input("How many names need to be entered?"))
names=make_list(number)
for name in names:
    if name[0]=="A":
        print("Name", name, "Starts with A")
  • Related