Home > Back-end >  Python if...in.. statement. Check for vowel in word
Python if...in.. statement. Check for vowel in word

Time:02-14

I'm new to python and i'm trying to check if the user input contains a vowel or not. But I only found how to check for one vowel at a time.. not all

vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")

This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]

any ideas how to check for e i o u at the same time?

CodePudding user response:

If you do not need to know which vowels are present, you can use any as follows.

vowels = ("a", "e", "i", "o", "u")

word = input("type a word: ")

if any(v in word for v in vowels):
    print("There is at least one vowel in your word.")
else:
    print("There is no vowel in your word.")

CodePudding user response:

One way to keep track is also to have an existence list that keeps all vowels that exist in a word.

existence = []
vowels = ["a","e","i","o","u"]
test_word = "hello" # You can change this to receive input from user

for char in  test_word:
    if char in vowels:
        existence.append(char)
if existence and len(existence) > 0:
    for char in existence:
        print(f"These vowels exist in your input {test_word} - {char}")
else:
     print(f"There are no vowels existing in your input {test_word}")

Output:

These vowels exist in your input hello - e
These vowels exist in your input hello - o

CodePudding user response:

A regular expression can tell you not only if there's a vowel in a string, but which vowels and their order.

>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']

CodePudding user response:

you have to iterate over the list.

vowels =  ["a","e","i","o","u"]

word = input("type a word: ")

for vowel in vowels:
  if vowel in word:
     print (f"There is the vowel {vowel} in your word")
  else:
     print ("There is no vowel in your word")

iteration is the proces where you go through each item in a list.

for example.

list_a = ['a', 'b', 'c' ]

for item in list_a:
  print(item)

#output will be a b c 

since other user complained in a comment. If you want to stop the loop after vowel found, you should add break statment

vowels =  ["a","e","i","o","u"]

word = input("type a word: ")

for vowel in vowels:
  if vowel in word:
     print (f"There is the vowel {vowel} in your word")
     break
  else:
     print ("There is no vowel in your word")
  • Related