'Enter names, display them as a list and print only the names that start with letter A from list
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?
Solution 1:[1]
Your method doesn't return the list, so default is
Noneyou need to give it back from itdef make_list(number): names = [] for item in range(number): names.append(input("Enter your name with a capital letter.")) return namesWhen 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 stringUse
str.startswithif name.startswith("A")
names = make_list(number)
for name in names:
if name.startswith("A"):
print("Name", name, "Starts with A")
Solution 2:[2]
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
Solution 3:[3]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | azro |
| Solution 2 | kvorobiev |
| Solution 3 |
