Python – Average word count 2

Hi, here is a kind of follow up for the 1st one. We, in this exercise , deal with leading space(s) , Boolean and punctuation.

def average_word_length(my_string):
    space_sayisi = 0
    word_sayisi = 0
    letter_sayisi= 0
    ortalam_word_uzunlugu = 0
    punctuation_sayisi = 0
    punctuation_listesi = ".,!? "
    try:
        uzunluk = len(my_string)
    except:
        return "Not a string"
    for i in range(0,uzunluk):
        if my_string[i] in punctuation_listesi:
            punctuation_sayisi += 1
        if punctuation_sayisi == len(my_string):
            return "No word"
        if my_string[i].isspace() and my_string[i+1].isalpha():
            space_sayisi += 1
            #print(space_sayisi)
    if my_string[0].isspace():
        space_sayisi -= 1
    word_sayisi = space_sayisi +1
    for i in range(0,uzunluk):
        if my_string[i].isalpha():
            letter_sayisi += 1
    ortalam_word_uzunlugu = letter_sayisi / word_sayisi
    return ortalam_word_uzunlugu





print(average_word_length("Hi"))
print(average_word_length("Hi, Lucy"))
print(average_word_length("   What   big spaces  you    have!"))
print(average_word_length(True))
print(average_word_length("?!?!?! ... !"))

The output will be;
2.0
3.0
4.0
Not a string
No word

Leave a Reply

Your email address will not be published. Required fields are marked *