Reputation: 29
Even a word that contains a vowel when entered outputs "NO VOWELS HERE!". Why? Please assist.
vowels = 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'
I = input("enter your name")
L = list(I)
print(L)
if vowels in L:
print("your name contains a vowel")
else:
print("NO VOWELS HERE!")
Upvotes: 1
Views: 1076
Reputation: 15872
You can use the intersection property of set
for this:
vowels = set('aeiouAEIOU')
I = set(input("enter your name"))
if len(I & vowels)>0:
print("your name contains a vowel")
else:
print("NO VOWELS HERE!")
Explanation:
>>> vowels = set('aeiouAEIOU')
>>> vowels
{'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'}
>>> I = set('John Doe')
>>> I
{' ', 'D', 'J', 'e', 'h', 'n', 'o'}
>>> (vowels & I)
{'e', 'o'}
{'e','o'}
present in both strings.
Upvotes: 2
Reputation: 13222
You have to compare each individual vowel.
vowels = 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'
name = input("enter your name")
if any(vowel in name for vowel in vowels):
print("your name contains a vowel")
else:
print("NO VOWELS HERE!")
As you can see in this code name
is not transferred to a list. You don't need that because a string is iterable. This means that you could do another change:
vowels = 'aAeEiIoOuU'
name = input("enter your name")
if any(vowel in name for vowel in vowels):
print("your name contains a vowel")
else:
print("NO VOWELS HERE!")
An example what happened in your original code:
>>> needle = 'a', 'b'
>>> needle in list('ab')
False
Let's check the values:
>>> needle
('a', 'b')
>>> list('ab')
['a', 'b']
You test if the tuple ('a', 'b')
is an element of ['a', 'b']
. As you can see it is not. The elements of the list are 'a'
and 'b'
. To be True
the comparison would have to look like this.
>>> needle in [('a', 'b')]
True
You have to understand that you're comparing the exact tuple, not parts of it.
>>> needle in [('a', 'b', 'c')]
False
Upvotes: 4