1

I am trying to write a program, that takes "source code" text file, and checks it line-by-line for more than two blank lines preceding a code line. I consider that line containing only whitespaces is blank.

My solution is to use global variable as a counter for preceding blank lines:

import os
import re


blank_lines_counter = 0

def check_blank_lines(line):
    global blank_lines_counter

    if re.match('^\s*$', line):
        blank_lines_counter += 1
    else:
        if blank_lines_counter > 2:
            blank_lines_counter = 0
            return True
        blank_lines_counter = 0
    return False

with open('input_file.py', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    
    for i, line in enumerate(lines, 1):
        if check_blank_lines(line):
            print(f'Line {i}: More than two blank lines used before this line')

But I don't like it because of global variable. Is there any way to rewrite this code in more fancy way and not using global variables, but still in procedural programming paradigm (not OOP)?

Maxim
  • 11
  • 2

2 Answers2

3

I would heavily suggest learning/using OOP in python (It's super useful!)
If you don't want to however, you could remove the use of the global keyword by passing the blank_lines_counter as a function parameter instead, it would look something like that:

def check_blank_lines(line: str, blank_lines_counter: int):
   [...]
   blank_lines_counter += 1
   return True, blank_lines_counter 
[...]

line_is_blank, blank_lines_counter = check_blank_lines(line, blank_lines_counter)
if line_is_blank:
    print(f'Line {i}: More than two blank lines used before this line')

Ellipses for brevity

Paolo Sini
  • 176
  • 10
2

You can pass it as a parameter to function.

Like,

def check_blank_lines(line, counter):
    ...
    return True, counter

counter = 0
for i, line in enumerate(lines, 1):
    is_blank, counter = check_blank_lines(line, counter)
    if is_blank:
        ...
shaik moeed
  • 5,300
  • 1
  • 18
  • 54