简体   繁体   中英

Can't get python function to return correct values

This is my first post here, but I will try to be short and clear on what I'm trying to solve. This is part of a homework assignment but not the actual assignment.

I'm having problems getting the function below to return the correct answers. I keep getting 0

The csv file is located in the same directory as the python file.

import csv

def count_matches(rows, field, value):
    count = 0
    for row in rows:
        if row[field] == value:
            count += 1
        return count

with open('hospitals.csv') as f:
    reader = csv.DictReader(f)
    hospitals_table = list(reader)


print(count_matches(hospitals_table, 'State', 'NY'))

I try hard coding it to see if I could get it to work outside the function (see below), and it works, returning the correct answer of 194 (hospitals in NY from the csv file). What am I doing wrong in the function? Thank you

import csv


with open('hospitals.csv') as f:
    reader = csv.DictReader(f)
    hospitals_table = list(reader)

count = 0
field = input('Enter field: ')
value_entered = input('Enter state: ')
for row in hospitals_table:
    if row[field] == value_entered:
        count += 1

print(count)

Your return statement is in the for loop therefore will return count on the first iteration. The loop must be outside or else it will just instantly return.

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