python 3.x - What is wrong with this program? Why did number and totalLength 0? -


why number , totallength still 0? doing wrong. should have changed due line in lines statement

def cleanedup(s):     alphabet= 'abcdefghijklmnopqrstuvwxyz'     cleantext = ''     character in s.lower():         if character in alphabet:             cleantext += character     else:             cleantext = ' '     return cleantext  import shelve  shelf = shelve.open('books') lines = shelf['pride , prejudice'] shelf.close()  number = 0 totallength = 0  line in lines:     word in cleanedup(line).split():         number += 1         totallength += len(word)  print(totallength, number) 

this main problem script:

        character in s.lower():             ...         else:             cleantext = ' ' 

i'm not sure right position else, in case you've put after loop, cleantext reset each time run function because loop has no break statement inside. more info on for ... else ...


although might not want (question little unclear), following code works:

def cleanedup(s):     alphabet= 'abcdefghijklmnopqrstuvwxyz'     cleantext = ''     character in s.lower():         if character in alphabet:             cleantext += character     return cleantext   lines = ['lorem ipsum dolor sin amet', 'foo bar']  number = 0 totallength = 0 line in lines:     word in cleanedup(line).split():         number += 1         totallength += len(word)  print(totallength, number) 

output:

>>> 28 2  # 28 = total number of characters, 2 = total number of lines 

ps: next time, provide more concise example demonstrates problem, instead of using external file.


Comments