Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
loop doesn't work - need help
I am trying to create a program where the user enters a letter (eg "D") and retrieves a name of names, from a LIST. I have two issues
- if user types "D" is only retrives on item in the list, when there are two
- if user does get the right item, it still runs the "else" section and print
what am I doing wrong? Thanks
see file with swith.py (https://w.trhou.se/dtygos96sc)
this program utilises the startswith() function
video_games = ["Destiny", "Origins", "Division"] cool_movies = ["Aliens", "Guardians", "Hitman"]
def ask_char(char, user_list): new_list = for string in user_list: if string.startswith(char): new_list.append(string) print(new_list)
else: print("cant find your choice. See list available") print(video_games) break
char = input("what letter do you want, use uppercase? ") ask_char(char, video_games)
Hello Sabry. You're on the right way and you will find your code making more sense with a few small adjustments.
Right now input "D" will result in the list video_games to be searched one string at a time. Since "Destiny" starts with a "D" it will add this to the new_list and then print it. On the first round, the else will therefore not fire. On the second round, however "else" will be activated since Origin does not start with a "D". It will print the feedback message, the whole list of video games (instead of the new list) and then break out of the loop.
What you probably want to do is remove all printouts and the else section (alternatively you could also change the break to a continue), use a second if statement after the first to test if the list is empty or not and then print either the new_list or a message saying that the list does not contain words starting with the specified letter. This way every string will be checked and added to the new_list if it starts with the desired character and the result will be based on the list as a whole.
I hope this helps. Do let me know if you have further questions.
PS. I agree with Steven on the formatting (it's faster to read with the right formatting) but could luckily open the workspace file.