3

I am trying to write a code with python that will find and count the number of vowels in any given string. My function prints out 0 vowels no matter what. Any tips?

txt = input("Type text: ").lower()

def findVowels():
    global txt
    vowels = 0
    for letter in txt:
        if letter == 'aeiouy':
            vowels += 1
    return vowels


print(findVowels())

Number of vowels = 0 no matter what

4
  • This is may not be code related but technically, "y" is not a vowel. Commented Oct 2, 2019 at 9:00
  • @CodeRed In English, "y" is considered as a vowel when it is not the first letter of syllable within a word. I.e. it is a consonant in the word "yup", but a vowel in the word "symbol". Commented Oct 2, 2019 at 9:02
  • I'd love to explain but this is not the best platform for that. Good day sir! Commented Oct 2, 2019 at 9:06
  • In my language, Norwegian "y" is a vowel so that's why it's in there Commented Oct 11, 2019 at 13:29

2 Answers 2

4

Try like this:

def findVowels(txt):
    return sum(1 for t in txt if t in 'aeiouy')
Sign up to request clarification or add additional context in comments.

3 Comments

Double def and you can even do: return sum(t in 'aeiouy' for t in txt)
Why couldn't you?
@schwobaseggl Thanks for the heads up, and you can, but tends to be slower do to conversion of bool to int.
2

You are checking if the letter is equal to the entire string 'aeiouy'. Instead check if letter is in the string.

if letter in 'aeiouy':

Also, you can avoid using global variable by passing the input text to the function.

txt = input("Type text: ").lower()

def findVowels(txt):
    vowels = 0
    for letter in txt:
        if letter in 'aeiouy':
            vowels += 1
    return vowels


print(findVowels(txt))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.