Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I'm reading head first programming, chapter 5. In this chapter, a program is written to get a contestant's details by inputting a number as an id. The program does this by searching through a csv file named "surfers_data.csv".
Whenever I run it, it returns nothing as results; it seems that no contestants owns this id; however there is one.
Here is the code:
SQL
def find_details(id2find):
    surfers_f=open("surfing_data.csv")
    for line in surfers_f:
        s={}
        (s['id'],s['name'],s['country'],s['average'],s['board'],s['age']) = line.split(";")
        if id2find==int(s['id']):
            surfers_f.close()
            return s
        surfers_f.close()
        return ({})

lookup_id = int(input("Enter the id of the surfer: "))
surfer = find_details(lookup_id)
if surfer:
    print("ID: " + surfer['id'])
    print("Name: " + surfer['name'])
    print("Country: " + surfer['country'])
    print("Average: " + surfer['average'])
    print("Board type: " + surfer['board'])
    print("Age: " + surfer['age'])


And the output is:
>> Enter the id of the surfer: 104 #I input this number as the id
>>#prints nothing as the result

Note: The csv file is accessible here: http://headfirstlabs.com/books/hfprog/chapter05/surfing_data.csv[^]
Posted
Updated 16-Aug-15 8:58am
v2

1 solution

You should try this
SQL
def find_details(id2find):
    surfers_f=open("surfing_data.csv")
    for line in surfers_f:
        s={}
        (s['id'],s['name'],s['country'],s['average'],s['board'],s['age']) = line.split(";")
        if id2find==int(s['id']):
            surfers_f.close()
            return s
    surfers_f.close()
    return ({})

Pay attention to the last 2 lines.
 
Share this answer
 
Comments
Daniel Saki 16-Aug-15 14:48pm    
Thanks a lot, my friend! I didn't pay attention to the if condition.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900