Joseph Joseph - 1 month ago 5
Python Question

Definition help count_engcons


Define a function called
count_engcons()
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
count_engcons("Tessellated?")
should return
7
, and
count_engcons("Aeiou!")
should return
0
. You must use a
for
loop, and
you are not allowed to use the
.count()
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.

Answer

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