As the title states, I'm trying to create (def) a function wherein I import re and then parse through a string (using Regular Expressions) to add the numbers up at the end in a list. I know the code works outside of the function I am trying to save. I've just never created a function this complex so I'm unsure of indentation usage or if it's possible.
Edit: After indenting my 'print' statement, the function does work. However it prints out all 87 lines and the sum per line. I had it on the outside of the loop so that it would only show one line. I just want it to show the last line (total sum and how many lines were counted). Before while working on this outside of the function I attempted to splice but that didn't work. I have also only been working with Python for maybe 5 days so please be gentle lol. I often go back and review material or google for an answer I can understand.
#create function to import the re lib and then parse through "fhand" after the file is opened by calling this function.
def Ptfs():
import re
count = 0
total = list()
for line in fhand:
numbers = re.findall('[0-9]+' ,line)
for number in numbers :
num = int(number)
total.append(num)
count = count + 1
print(sum(total), "There were", count, "lines that were summed.")
fhand = open("file_name", 'r')
Ptfs()
There's a few improvements you can make - hopefully this a) works and b) does the same thing you were doing...
import re # don't import modules inside functions
def Ptfs(filename): # pass filename into function
count = 0
total = 0 # calculate total as we go
with open(filename) as fhand: # use with so file gets closed automatically
for line in fhand:
numbers = re.findall('[0-9]+' ,line)
for number in numbers :
total += int(number)
count += 1 # shorthand for count = count + 1
return count, total
# pass filename into function and return count and total
count, total = Ptfs("file_name")
# use f-strings to format output
print(f"{total} There were {count} lines that were summed.")