Is there a better way to group "Ors" in Python without having to type the variable all the time?

Asked

Viewed 71 times

3

Example:

letra = input('Digite uma letra: ')


if(letra == 'a' or letra == 'e' or letra == 'i' or letra == 'o' or letra == 'u'):

        print('Vogal')

1 answer

4


You can use the operator in:

letra = input('Digite uma letra: ')
if letra in ('a', 'e', 'i', 'o', 'u'):
    print('Vogal')

Of course if you just want to do the check and then you won’t use the letter for anything else, nor need a variable:

if input('Digite uma letra: ') in ('a', 'e', 'i', 'o', 'u'):
    print('Vogal')

And before anyone suggests, there is an alternative that works for these cases, but with a few points:

if letra in 'aeiou':

The problem is that in this case also if if the user types aei, for example, since the operator in, when applied to a string, checks whether letra is a substring of aeiou. If you want the options to be only the vowels (i.e., the variable letra can only have one character), use the previous option.


Another alternative - unnecessarily complicated for this case - is to use regex (available on module re):

import re

if re.match('^[aeiou]$', input('Digite uma letra: ')):
    print('Vogal')

In this case, regex checks whether the string contains only one of the letters ("a", "e", "i", "o" or "u"). It uses the markers ^ and $ which indicate respectively the beginning and end of the string, thus ensuring that it only has what is in the expression. It also uses the character class [aeiou], that picks up any of the vowels.

But for a simple case like this, using regex is an exaggeration, I left only as curiosity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.