I'm having a slight problem with counting newlines. I'm working on a program that's supposed to count items from a .txt file (characters, upper/lowercase characters, etc.). However, my line counter is counting the amount of character plus one instead of the amount of new lines. For instance, instead of getting something like a character count of 1048 and a line count of 37, I get a character count of 1048 and a line count of 1049. I'm not sure where I messed up.
Below is the relevant code. I appreciate any assistance.
# initializing counters char_count = 0 lower_count = 0 upper_count = 0 lines_count = 0 word_count = 0 prev_ch = ' ' is_prev_alnum = False for ch in contents: char_count += 1 if ch.islower(): lower_count += 1 if ch.isupper(): upper_count += 1 if ch == '\n': lines_count += 1 # count words if ch.isalnum(): if not is_prev_alnum: word_count += 1 is_prev_alnum = True else: is_prev_alnum = False if prev_ch != '\n': lines_count += 1 prev_ch = ch
if prev_ch != '\n'. I think you mean to checkif prev_ch == '\n'. In other words, count a new line for every\n.