Home > Mobile >  Can't get python function to return correct values
Can't get python function to return correct values

Time:11-25

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)

CodePudding user response:

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.

  • Related