How to make it so if first character is 'a' immediately exit loop with message in python

Viewed 53

I am trying to do an assignment where it requires me to indicate that if there is a word that starts with a in the list, there must be a break and message indicating as such. This is what I have so far but not sure where to go from here or how to fix it.

mylist = ['bananas', 'grapes', 'pears', 'peaches', 'apples', 'plums', 'oranges']

result = [i for i in mylist if i.startswith('a')]

for letter in mylist:
    if letter == 'a':
        break
        print("Found word starting with 'a'. Exiting loop.")
1 Answers

You're on the right track, you just need to put components from the for loop and the list comprehension together:

for word in mylist:
    if word.startswith('a'):
        print("Found word starting with 'a'. Exiting loop.")
        break

This outputs:

Found word starting with 'a'. Exiting loop.

As an aside, we can usually describe this pattern of looping until we see an item that meets a condition using any() (not immediately relevant to the question at hand, but can be handy, so I've included it for completeness):

if any(word.startswith("a") for word in mylist):
    print("Found word starting with 'a'. Exiting loop.")
Related