Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python count lines with numbers less than, or more than

Tags:

python

I'm new to python and writing a program to count lines. the file looks like this:

  0.86149806
  1.8628227
 -0.1380086
 -1
  0.99927421
 -1.0007207
  0.99927421
  0.99926955
  -1.0007258

And my code attempt is the following:

counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('test.txt', 'r') as infile:
    for line in infile:
        counterTot += 1
        for i in line:
            if i > 0.3:
                counterPos += 1
            elif i < -0.3:
                counterNeg += 1
            else:
                counterNeu += 1

I'm trying to get it to count all lines lower than -0.3 to counterNeg, all lines above 0.3 as counterPos, and all lines that have a number between 0.29 and -0.29 to counterNeu.

It doesn't seem to work though, I know im going wrong with for i in line but not sure how.

like image 891
RHK-S8 Avatar asked Nov 21 '25 15:11

RHK-S8


1 Answers

Your line is a string, but you want to parse it as a float. Just use float(line).

It's also better to strip all whitespace from the beginning and end of your line just in case. So:

for line in infile:
    i = float(line.strip())
    # ... count
like image 81
kirelagin Avatar answered Nov 24 '25 05:11

kirelagin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!