Reputation: 133
I have a program in which a user picks a letter. The program should then search through a list and count how many names start with the letter the user chose.
This is what I've got so far:
nameslist = ["bob", "phil", "james"]
letter = input("Pick a letter.")
letter = letter.lower()
wordcount = 0
for I in range(len(nameslist)-1):
if list[I].startswith(letter):
wordcount = wordcount+1
print(list[I])
I was led to believe that startswith
would help me but it doesn't work.
Upvotes: 1
Views: 2206
Reputation: 3891
If you want to keep your current code all you need to do is fix some typos. Here is the correct code with comments showing what I changed:
nameslist=["bob","phil","james"]
letter=input("Pick a letter.")
letter=letter.lower()
wordcount=0
for I in range(len(nameslist)): # you dont need the -1 at the end of this
if nameslist[I].startswith(letter): # you need to change list to nameslist
wordcount=wordcount+1
print(nameslist[I]) # you need to change list to nameslist
Upvotes: 4
Reputation: 11961
You could use the following:
names = ["bob","phil","james"]
letter = input("Pick a letter.")
letter = letter.lower()
count = 0
for name in names:
if name.startswith(letter):
print(name)
count += 1
This iterates over each name
in names
and uses the startswith()
method to check whether name
begins with letter
. If name
begins with letter
, it prints name
. It also counts the number of name
in names
that begin with letter
using the count
variable.
Upvotes: 7