Vikas Rajasekaran
Vikas Rajasekaran

Reputation: 71

My function doesn't return a value, can't figure out why

The function is supposed to open a csv file that has data in this format

"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"

When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe there is an issue with the rest of the code as if I replaced 'return poll data' with 'print(poll_data)' there is the desired output.

I am a noob at this and don't have a full grasp of return.

def read_data_file(filename):
    file = open(filename, 'r')
    poll_data = []
    for data in file:
        data = data.strip('\n')
        data = data.split(',')
        poll_data.append(data)
    return poll_data


read_data_file('florida-gop.csv')

Upvotes: 3

Views: 185

Answers (3)

Coolq B
Coolq B

Reputation: 354

Continuing from the above(or not so above anymore xD) answer...

the full code would now be,

def read_data_file(filename):
    file = open(filename, 'r')
    poll_data = []
    for data in file:
        data = data.strip('\n')
        data = data.split(',')
        poll_data.append(data)
    return poll_data


print(read_data_file('florida-gop.csv')) # Before you forgot to print it.

or exactly like the above answer,

def read_data_file(filename):
    file = open(filename, 'r')
    poll_data = []
    for data in file:
        data = data.strip('\n')
        data = data.split(',')
        poll_data.append(data)
    return poll_data


data = read_data_file('florida-gop.csv')
print(data)

Upvotes: 0

n1c9
n1c9

Reputation: 2687

you changed that last line in the function from print to return. So, when you call your function as such:

read_data_file('florida-gop.csv')

it does return that data. It's sitting right there! But then your script ends, doing nothing with that data. so, instead, do something like this:

data = read_data_file('florida-gop.csv')
print(data)

a short addendum - political data is an excellent way to learn data manipulation with Python and, if so inclined, Python itself. I'd recommend the O'Reilly books on data & Python - but that's outside the scope of this question.

Upvotes: 2

auden
auden

Reputation: 1157

You have two options here:

  1. Replacing return poll_data with print poll_data.
  2. Instead of read_data_file('florida-gop.csv'), you can do print read_data_file('florida-gop.csv').

Why do you need to do this?

Print vs Return

print actually shows you the result, while return only gives the result to the computer, if that makes sense. The computer knows it, but it doesn't print it, which is why the second solution works - the computer has the data you want, and it is able to print it if you command it too. However, in your case, the first solution is probably easier.

Hope this helps!

Upvotes: 1

Related Questions