-3

My Code:

VowelsInString = False
String = 'bbbb000'
if 'a' or 'e' or 'i' or 'o' or 'u' in String:
  VowelsInString = True
elif 'a' or 'e' or 'i' or 'o' or 'u' not in String:
  VowelsInSting = False

So, I was expecting that when this ran, the if statement would be skipped and the VowelsInString would remain False, but upon running the code, the value of VowelsInString is True.

I expect that I may have done something wrong whilst typing the vowel checker if argument as I am fairly new to the concept of reading characters in strings. I would appreciate if someone would help me on debugging this code.

If that however is not the case, than I would, again, appreciate if someone would help on telling me what I've done wrong.

4 Answers4

1

'a' or 'e' or 'i' or 'o' or 'u' in String:

evaluates as

('a') or ('e') or ('i') or ('o') or ('u' in String).

Since 'a' is truthy in python, this evaluates to True.

You can either write

if 'a' in String or 'e' in String ...

or

def has_vowel(String):
    for s in String:
        if s in 'aeiou':
            return True

or perhaps

if any(s in String for s in 'aeiou'):

or (credit to Onyambu):

import re
...
re.search('[aeiou]',string)
Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
0

Your conditions is a tautology:

if 'a':
    print("I am always going to print")
Luca Cappelletti
  • 2,485
  • 20
  • 35
0

Looks like you are evaluating the character itself as a bool.

It is detecting 'a' as True and returning true.

Try something more like:

if any(i in '<string>' for i in ('a','b','c')):

see: How to check a string for specific characters?

Brad Fallon
  • 169
  • 1
  • 7
  • 1
    You can just do `for i in 'abc'` here, since strings are iterables of their characters. But, while that might be more readable for experienced Python devs, it might be less readable to novices, so I'm not sure whether the tradeoff is worth it in this case. – abarnert Jul 30 '18 at 19:10
0

'a' or 'e' or 'i' or 'o' or 'u' in String is always true. What you meant to do is:

if 'a' in String or 'e' in String or ...:

Or, using any:

if any(c in String for c in 'aeiou'):
user2390182
  • 72,016
  • 6
  • 67
  • 89