user6077707
user6077707

Reputation:

I need assistance with a program that would find words starting with a letter i type in

Right now all my code does is find all the a's in all my words. All I want it to do is find words that start with the letter I type using that letter to find the words. E.g. A would find the words activity, again and ago. I have tried looking every where and can't find the answer I need.

dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':

    choice = input("?")
    if choice == 'a':
    for a in dictionary:
        newlist.append(choice.lower())
        print(newlist)

Upvotes: 0

Views: 91

Answers (3)

jDo
jDo

Reputation: 4010

Python strings actually have a startswith method :) It's equivalent to string[0] in your case.

dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':
    choice = input("?")
    for a in dictionary:
        if a.startswith(choice.lower()):
            newlist.append(a)
    print(newlist)

Upvotes: 1

user6077707
user6077707

Reputation:

Incase any one needs the code and runs into the code printing for awhile. This should help with that:

count = 0
while count < len(newlist):
    count = count + 1
    print(newlist)
    length = len(newlist)

Upvotes: 0

Zac Bowhay
Zac Bowhay

Reputation: 26

dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':

choice = input("?")
if choice == 'a':
    for item in dictionary:
        if(item[0] == choice):
            newlist.append(item)
    print(newlist)

Your above code isn't checking against the first character of each item in the dictionary. It is simply running through every item in the dictionary and appending your "choice" (in this case 'a') to the "newList" and then printing the current items in "newList"

To fix that you need to check the first letter of each item in your dictionary against your choice and then only append those particular items to your "newList"

Upvotes: 1

Related Questions