Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading