Another question.
This program counts and numbers every line in the code unless it has a hash tag or if the line is empty. I got it to number every line besides the hash tags. How can I stop it from counting empty lines?
def main():
file_Name = input('Enter file you would like to open: ')
infile = open(file_Name, 'r')
contents = infile.readlines()
line_Number = 0
for line in contents:
if '#' in line:
print(line)
if line == '' or line == '\n':
print(line)
else:
line_Number += 1
print(line_Number, line)
infile.close()
main()
You check if
line == '' or line == '\n'inside theifclause for'#' in line, where it has no chance to beTrue.Basically, you need the
if line == '' or line == '\n':line shifted to the left 🙂Also, you can combine the two cases, since you perform the same actions:
But actually, why would you need printing empty stings or
'\n'?Edit:
If other cases such as
line == '\t'should be treated the same way, it’s the best to use Tim’s advice and do:if '#' in line or not line.strip().