17/19: A better way to write OR statements without repeating criteria


#1

Here is my code for this exercise, which I modified a little to slightly improve the grammar (for handling vowels and consonants with "An" and "A" repectively. e.g. "An orange", "A banana".) :

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

i = 0
print 'You have...'
for fruit in sorted(fruits):
    if fruit == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    elif sorted(fruits)[i][0] == "a" or sorted(fruits)[i][0] == "e" or sorted(fruits)[i][0] == "i" or sorted(fruits)[i][0] == "o" or sorted(fruits)[i][0] == "u":
        print 'An', fruit
        
    else:
        print 'A', fruit
    i += 1
else:
    print 'A fine selection of fruits!'

My question, which applies much more generally than for this specific exercise, is:

  • How can we test multiple OR statements, using the same criteria, in a more succinct way than writing the criteria repeatively, as I have done in the elif statement:

elif sorted(fruits)[i][0] == "a" or sorted(fruits)[i][0] == "e" or sorted(fruits)[i][0] == "i" or sorted(fruits)[i][0] == "o" or sorted(fruits)[i][0] == "u":

I want to write it something like:
elif sorted(fruits)[i][0] == "a" or "e" or "i" or "o" or "u"

Any suggestions?? (the last one directly above does not work).

Thanks for any help: I am sure I will use this HEAPS going forward!!


#2

Do something simple if you want to know if a vowel is at the start of a string simply do as follows.

a_string = 'string'
if a_string[0].lower() in 'aeiou':
    print(True)
else:
    print(False)

You can do similar things with lists.

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
if 'tomato' in fruits:
    print(True)
else:
    print(False)

On to the or statements.

It can work like this,

a = 'string'
if ('a' or 'e' or 'i' or 'o' or 'u') in string.lower():
    print(True)
else:
    print(False)

Sometimes you just have to think creatively to encompass all your conditions.


#3

Thanks zeziba. Your first one works well in my code (although not technically using OR - it does the job), namely by replacing the elif code to this:

elif sorted(fruits)[i][0] in 'aeiou':

(Note that your other proposed solution Doesn't work (as is): as it looks for a vowel in any location in the word (not just the first letter), and changing it to try and only look in the first letter of each list entry doesn't work either (well not easily anyway):

 elif ("a" or "e" or "i" or "o" or "u") in sorted(fruits)[i][0]:

(Since the first one works perfectly I'm happy and will try to work on my creativity! Cheers again.)