简体   繁体   中英

How use two different loops under a for loop in python

We have to compute how many times a number greater than 130 and a number less than -70 occurred in the 2nd column of each row in an excel sheet, saved as a csv file. I need a loop but i already had a loop above it for computing a different column in the rows. I can't seem to get a code that loops around all the row[4] and compute it into one variable. Here is my code.

import csv
import os
total = 0
count = 0
ring = 0
column = []
with open("2.5_week.csv") as source:
    rdr = csv.reader(source, delimiter=',')
    next(rdr, None) # to skip the header

    for row in rdr:
        if float(row[4]):
            total = total + float(row[4])
            count = count + 1  
        while (float(row[2]) >= 130 and float(row[2]) <= -70):
            ring = ring + 1
            print(ring)
        percent = (ring/count) * 100
        ave = total / count
    print (ave, percent)

It works for the if loop and prints the 'ave' but seems to skip the while loop. Thanks in advance

The condition float(row[2]) >= 130 and float(row[2]) <= -70 is logically incorrect. Lets say the number is 230, so 230>=130 is true but 230<=-70 is false and hence the condition evaluates to false.

So use this:

while (float(row[2]) >= 130 or float(row[2]) <= -70) #or instead of and

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM