Joseph Joseph - 4 months ago 22
Python Question

Definition help count_engcons

Define a function called
which takes a string and
returns the number of consonants in the string (uppercase or
lowercase). For this problem, you may consider only letters in the
English language alphabet only. Also, for this problem "Y" is
considered a consonant (...not a vowel!). So for example
should return
, and
should return
. You must use a
loop, and
you are not allowed to use the
method on this problem.

I tried this:

def count_engcons(x):
vowels = ("aeiou")
count = 0

for count_engcons in text:
if not count_engcons in vowels:
count += 1
return x

However, it causes an error.


You were checking if a character wasn't a vowel, so it would give bad results for characters such as ! or ?, you were also trying to access the string with different variable names (x and text), which makes no sense.

def count_engcons(text):
    consonants = "bcdfghijklmnpqrstvwxyz"
    count = 0

    for c in text.lower():
        if c in consonants:
            count += 1

    return count