Trying to set up a function that counts the number float values contain inside a txt file when exceeds a custom limit:
count_out = 0
def testing(txts, limit, count_in):
#tried global but doesn't work
global count_out
text = text.strip()
values = float(text)
if values > limit:
count_in += 1
return count_in
However currently, it doesn't count the number of values pass through the limit and remain at default value of 0 :
for a in open('sample.txt'):
testing(a, 35, count_out)
print(count_out)
The values within the sample.txt are:
28.8
49.5
29.0
27.6
35.7
count_outto be global, you don't modify it insidetesting()count_outand changing it in the function won't change the contents of the original variable define outside the function (whether you declare itglobalor not).textis undefined in the code in your question and call the function will result in anUnboundLocalError: local variable 'text' referenced before assignment.