How to count vowels and consonants in Python? - python

I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.
1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.
2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.
Here is what I have:
def main():
user_input = input("Enter a string of vowels and consonants: ")
vowel_list = set(['a','e','i','o','u'])
countVowels(user_input, vowel_list)
countConsonants(user_input, vowel_list)
def countVowels(user_input, vowel_list):
user_input.lower()
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
def countConsonants(user_input, vowel_list):
user_input.lower()
index = 0
consonants = 0
while index < len(user_input):
if user_input[index] not in vowel_list:
consonants += 1
index += 1
print ('Your input has' , consonants , 'consonants.')
main()
Here is an IO:
Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.

Indentation is key.
The print should only happen after the while loop is done, so it must be indented the same as the while. The increment of the index is in the wrong spot as well: this must happen each time regardless of whether or not the if condition evaluates to True. (With your alignment, the index only increases past vowels and may never get far enough to allow the while loop to end; this is why you never got to countConsonants.)
Your countVowels function then becomes:
def countVowels(user_input, vowel_list):
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
By the way, consider using a for loop here over the characters in user_input instead of while and indexing; i.e. use something like:
for char in user_input:
if char in vowel_list:
vowels += 1

I read through your code and found a couple issues. You seem to not be calling .lower in the right spot. It doesn't modify the string, it simply returns a lowercase version of the string. And i combined your vowels and consonants with a little math. Additionally, I added a conditional for loop that will scan through the letters and pick all the vowels out, then it will take the length of the vowel list found. Finally, I also just combined vowel_list into a string to make it look prettier.
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = 'aeiou'
countVowelsAndConsoants(user_input, vowel_list)
def countVowelsAndConsoants(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', vowels , 'vowels.')
print ('Your input has', len(user_input)-vowels, 'consonants.')
main()
If you need them both separate:
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = 'aeiou'
countVowels(user_input, vowel_list)
countConsonants(user_input, vowel_list)
def countVowels(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', vowels , 'vowels.')
def countConsonants(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', len(user_input)-vowels, 'consonants.')
main()

##it is list
listChar = ['$','a','8','!','9','i','a','y','u','g','q','l','f','b','t']
c = 0##for count total no of elements in a list
cVowel = 0 # for count vowel
cConst = 0 # for count consonants
cOther = 0 # for count other than consonants and vowels
for i in listChar : ## use loop for count eaxh elements
c += 1
if i in 'aeiou' : ## check it is vowewl
cVowel = cVowel + 1 # count vowel
elif i in '!##$%^&*()+-*/123456789~`' : # other than alphabets
cOther = cOther + 1 # count other than alphabets elements
else :
cConst = cConst + 1 ## count consonants if above contion not satisfied
print all results
print ("total number of element in the list : ", c)
print("count vowels characters : ",cVowel)
print("count consonants characters : ",cConst)
print("count other characters : ",cOther)

I hope this is what you want. I replaced the while loop with the for loop and added a variable count_Consonant with a list of consonants.
def countVowels(user_input, vowel_list):
vowels = 0
for i in vowel_list:
if i in user_input:
vowels+=1
print ('Your input has {} vowels.'.format(vowels))
def countConsonants(user_input, count_Consonants):
consonants = 0
for i in count_Consonants:
if i in user_input:
consonants+=1
print ('Your input has {} consonants.'.format(consonants))
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = set(['a','e','i','o','u'])
countVowels(user_input, vowel_list)
count_Consonants = set(["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"])
countConsonants(user_input, count_Consonants)
main()

def VowCons(Str):
Vcount = 0
ConsCount = 0
Vowels = ['a','e','i','o','u']
for char in Str:
if char in Vowels:
Vcount +=1
else:
ConsCount +=1
print(Vcount," is the number of vowels and ",ConsCount," is the count of consonants")
VowCons("how many vowels and consonants are there")

Define a procedure is_vowel.
It takes your name as its input and prints:
‘Your name starts with avowel’
if it starts with a vowel, and prints ‘Your name starts with a consonant’, otherwise?
Example:
is_vowel(‘Ali’) ‘Your name starts with a vowel’
is_vowel(‘aqsa’) ‘Your name starts with a vowel’
is_vowel(‘Sam’) ‘Your name starts with a consonant’

Here is a program that counts vowels and consonants.
It makes use of a dictionary slice:
itemgetter(*vowel_or_consonant)(c) # slice
Script:
from collections import Counter
from operator import itemgetter
from string import ascii_letters
VOW = set('aeiouAEIOU')
CON = set(ascii_letters)-VOW
def letter_count(s, vowel_or_consonant):
c = Counter(s)
return sum(itemgetter(*vowel_or_consonant)(c))
s ="What a wonderful day to program"
print('Vowel count =', letter_count(s, VOW))
print('Consonant count =', letter_count(s, CON))
"""
================= RESTART: C:/Old_Data/python/vowel_counter.py =================
Vowel count = 9
Consonant count = 17
"""

Related

How to select certain characters in a string in Python?

My name is Shaun. I am 13 years old and trying to learn python.
I am trying to make a program that finds vowels in an input and then prints how many vowels there are in the input the user gives.
Here is the code:
s = (input('Enter a string: ')) # Let the user give an input (has to be a string)
Vwl = [] # Create an array where we will append the values when the program finds a vowel or several vowels
for i in s: # Create a loop to check for each letter in s
count_a = 0 # Create a variable to count how many vowels in a
count_e = 0 # Create a variable to count how many vowels in e
count_i = 0 # Create a variable to count how many vowels in i
count_o = 0 # Create a variable to count how many vowels in o
count_u = 0 # Create a variable to count how many vowels in u
The function below is pretty long to explain, so summary of the function below is to find a vowel in s (the input) and make one of the counters, if not some or all, increase by 1. For the sake of learning, we append the vowels in the array Vwl. Then, it prints out Vwl and how many letters there are in the list by using len.
if s.find("a" or "A") != -1:
count_a = count_a + 1
Vwl.append('a')
elif s.find("e" or "E") != -1:
count_e = count_e + 1
Vwl.append("e")
elif s.find("i" or "I") != -1:
count_i = count_i + 1
Vwl.append("i")
elif s.find("o" or "O") != -1:
count_o = count_o + 1
Vwl.append("o")
elif s.find("u" or "U") != -1:
count_u = count_u + 1
Vwl.append("u")
print(Vwl)
print(f"How many vowels in the sentence: {len(Vwl)}")
For some odd reason however, my program first finds the first vowel it sees, and converts the whole string into the first vowel it finds. Then it prints down the wrong amount of vowels based on the array of vowels in the array Vwls
Could someone please help me?
The reason your code only prints out the first vowel is because the if statements you coded are not inside a loop, that part of the code runs once and then it finishes, so it only manages to find one vowel.
Here are couple ways you can do what you are trying to do:
Way 1: Here is if you just want to count the vowels:
s = input()
vowel_counter = 0
for letter in s:
if letter in "aeiou":
vowel_counter+=1
print(f"How many vowels in the sentence: {vowel_counter}")
Way 2: Use a python dictionary to keep track of how many of each vowel you have
s = input()
vowel_dict = {}
for letter in s:
if letter in "aeiou":
if letter not in vowel_dict:
vowel_dict[letter]=0
vowel_dict[letter]+=1
print(f"How many vowels in the sentence: {sum(vowel_dict.values())}")
print(vowel_dict)

Python if...in.. statement. Check for vowel in word

I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but 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?
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.")
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
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']
I feel that if you want to use only if statements, then you can only choose one of the vowels but if you wish to use the for and if statements, it can go through with the whole vowels
I can solve your problem.
Here is the code:
vowels = {'a','e','i','o','u'}
word = input("Enter a word: ")
for vowel in word:
if vowel in vowels:
print(vowel,"is a vowel")
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")

Pig Latin Python program

I've been working on a Pig Latin program. However, it doesn't seem to be working and I can't figure out why.
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first == "a" or "e" or "i" or "o" or "u":
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
On top of that, I was looking to utilize enumerate to find the position of the first vowel, slicing to isolate the first letter of the word and concatenation to form the word. I've read up on how to use it on a couple websites but I can't seem to figure out how to correctly apply it to this program. I think I would have to define Vowels = 'aeiou' before def translate(user_input) right??
You cannot chain if statements like that in Python, you have to do it the long way:
if first == "a" or first == "e" or first == "i" or first == "u":
or shorten it to:
if first in ["a", "e", "i", "u"]:
Here is the solution. I've made a few changes in your code which i will be explaining below.
user_input = input("Enter word to be translated:\n")
#change_1
vowels = ['a','e','i','o','u']
def translate(user_input):
first = user_input[0]
#change_2
if first in vowels:
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
#change_3
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
#change_4
user_input = user_input[index_value:] +user_input[:index_value]+ "ay"
return user_input
print(translate(user_input))
1) Create a list of vowels.
2) As our friend #zwer mentioned You cannot chain if statements like that in
Python. So
if first in vowels:
3) For every letter in user_input check if that letter is a vowel and if that letter is a vowel then find the index of it's occurrence.
For example take the word 'trash'
Here a is the first vowel and it's index is 2
if letter in vowels:
index_value = user_input.index(letter)
4) According to wikipedia
"all letters before the initial vowel are placed at the end of the word sequence"
For the word 'trash' it would be
user_string = user_input[2:] + user_input[:2]+"ay"
which would be slicing the word from that index to end, merged with letters before that index. And finally an "ay".
'ash' + 'tr' + 'ay'
Hope this helps.
You can define vowels in the outer scope.
vowels = 'a', 'e', 'i', 'o', 'u'
Then anywhere you can use:
if first in vowels:
My Solution covers the below rules:
1. A word is a consecutive sequence of letters (a-z, A-Z) or apostrophes. You may assume that the input to the function will only be a single "word". Examples: Zebra , apple
2. If a word starts with a vowel, the Pig Latin version is the original word with "way" added to the end
3. If a word starts with a consonant, or a series of consecutive consonants, the Pig Latin version transfers ALL consonants up to the first vowel to the end of the word, and adds "ay" to the end.
4. The letter 'y' should be treated as a consonant if it is the first letter of a word, but treated as a vowel otherwise.
5. If the original word is capitalized, the new Pig Latin version of the word should be capitalized in the first letter. If the original capital letter was a consonant, and thus moved, it should not be capitalized once in its new location.
Solution Starts here:
eng_to_pig_latin = {"football": "ootballfay", "Pittsburgh":"Ittsburghpay",
"Apple":"Appleway","oink":"oinkway",
"ontology":"ontologyway","yellow":"ellowyay","yttrium":"iumyttray"}
eng_word = 'yttrium'
vowels = 'aeiou'
def pig_latin(eng_word):
sub,str1 = [],''
first = eng_word[0]
second = eng_word[1]
# Rule 2
if first.lower() in vowels:
piglatin = eng_word +'way'
# Rule 3
elif first.lower() == first and second.lower() in vowels:
piglatin = eng_word[1:]+first+'ay'
elif first.lower()+second.lower() not in vowels:
# Rule 3 & 4
for l in eng_word:
if l not in vowels:
sub.append(l)
else:
str1 = eng_word[eng_word.index(l):]
break
str2 = ''.join(sub)
piglatin = str1+str2+'ay'
else:
# Rule 5
piglatin = eng_word[1:].capitalize()+first.lower()+'ay'
print(f'Test word is {eng_word} and its equivalent piglatin word is
{piglatin}. Comparison with mapping dictionary is
{eng_to_pig_latin[eng_word] == piglatin}')
pig_latin(eng_word)
Note: The dictionary uses is only to cross-check if the results are as expected, which I am doing in the last print statement.
my logic to translate given word in to Pig Latin translation
vowels=['a','e','i','o','u']
def igpay(name):
a_list=list(name)
if a_list[0] in vowels:
print("First letter is a Vowel")
apnd_letters="way"
else:
print("First letter is a Consonant")
a_list.append(a_list[0])
a_list.pop(0)
apnd_letters="ay"
print("Pig transaltion is {0}".format("".join(a_list)+str(apnd_letters)))
Output:
igpay("pig")
First letter is a Consonant
Pig transaltion is igpay
igpay("apple")
First letter is a Vowel
Pig transaltion is appleway
You can do it exactly the same as you are doing it except you will need to change the second line in translate:
if first == "a" or "e" or "i" or "o" or "u":
to:
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
or:
if first in 'aeiou':
If you want to be able to use capital letters however, I would recommend changing first to first.lower().
This becomes:
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first.lower() in 'aeiou':
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
If you want the code a bit shorter, I have managed to shorten it to:
def translate():
user_input = input('Enter a word or sentence')
for i in range(len(user_input.split())): print(str((user_input.split())[i][1::])+((user_input.split())[i])[0]+'ay', end=' ')
translate()
Here is another two ways to go about it
Method 1:
Using a function that recursively translates words
sentence = str(input('Input Sentence: '))
vowels = 'aeiouAEIOU'
# 1. strip removes whitespace before and after input
# 2. pig_word_latin deals with one word at a time
# 3. join collects all the words into one sentence with spaces
def pig_latin_word(word):
vowelStart = True
#print(word)
if word[0] not in vowels:
vowelStart = False
return pig_latin_word(word[1:] + word[:1])
elif word[0] in vowels and not vowelStart:
return word + 'ay'
elif word[0] in vowels and vowelStart:
return word + 'way'
def pig_latin(sentence):
words: list = sentence.strip().split(' ')
new_words = []
for word in words:
new_words.append(pig_latin_word(word))
print(" ".join(new_words))
pig_latin(sentence)
Method 2:
Using a function that recursively translates sentences by keeping track of spaces
sentence = str(input('Input Sentence: ')).strip()
vowels = 'aeiouAEIOU'
suffix = {}
suffix[True] = 'way'
suffix[False] = 'ay'
def pig_latin(sentence, acc='', cluster='', word=''):
#print('S:'+sentence, 'C:'+cluster, 'W:'+word)
#print('Acc:',acc)
new_word = len(word)==0
vowel_start= len(cluster)==0
#print('NW:',new_word, suffix[vowel_start])
#print('-')
if len(sentence) == 0:
return acc+word+cluster+suffix[vowel_start]
if sentence[0] == ' ':
return pig_latin(sentence[1:], acc+word+cluster+suffix[vowel_start]+' ')
if new_word == True:
if sentence[0] not in vowels:
#print('1---')
return pig_latin(sentence[1:], acc, cluster+sentence[0], '')
elif sentence[0] in vowels and not vowel_start:
#print('2---')
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
elif sentence[0] in vowels and vowel_start:
#print('3---')
return pig_latin(sentence[1:], acc, '', word+sentence[0])
else:
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
print(pig_latin(sentence))

List slicing issues in python

This code seems like it should work. It sums up the number of words that are "striped" (letter-consonant-letter-etc.) and then returns the sum. However when I test it with print (striped("My name is ...") ) it only counts my and is and gives me a sum of 2 instead of 3... why is name missing?
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((word[::2] in vowels and word[1::2] in consonants)\
or (word[::2] in consonants and word[1::2] in vowels))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
Here is a solution with lists. The problem with your code is that words longer than two characters return a substring when you use [::2] rather than single characters that are tested whether they are contained in vowels / constants.
By converting it to a list first, you can check every item of the list whether it is contained in the according set of characters.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((all(c in vowels for c in list(word[::2]))\
and all(c in consonants for c in list(word[1::2])))\
or (all(c in consonants for c in list(word[::2]))\
and all(c in vowels for c in list(word[1::2]))))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
print striped("My name is")
You should use set.issubset() instead.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = set(c for c in VOWELS.lower())
consonants = set(c for c in CONSONANTS.lower())
for word in text:
word = word.lower()
if ((set(word[::2]).issubset(vowels) and set(word[1::2]).issubset(consonants))\
or (set(word[::2]).issubset(consonants) and set(word[1::2]).issubset(vowels)))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
striped('My name is...')
The reason it works for my and is is that they are two char words, so you are checking if if m is in the string of constants, and if y is in the string of vowels, which works. For longer words like name, then clearly nm is not in the string of sonsonants, so it fails.
Instead, you should use sets. Essentially, you want to find if set(['n','m']) is a subset of the set of consonants.

checking if the first letter of a word is a vowel

I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.

Categories