0

Good Evening, I'm having some trouble with my code. My objective here is to input data into a class. So I have p1 = Pitch("CH", "S"). From here I want to run a function that prints a statement with this data entered with another function that finds the avg speed also inside the print statement. My bad if this isn't making to much sense but let me post my code that I have so far to see if it gives a better visual.

import csv

fh = open('pitches.csv')
spreadsheet = csv.DictReader(fh)

startspeed = []

class Pitch:
    def __init__(self, name, result):
        fh = open('pitches.csv')
        self.spreadsheet = csv.DictReader(fh)
        self.name = name
        self.result = result

    def avg_start_speed(self):
        for row in spreadsheet:
            if row['pitch_type'] == str(self.name) and row['type'] == str(self.result):
                startspeed.append(row['start_speed'])
        return sum(startspeed) / len(startspeed)


    def myfunc(self):
        for row in spreadsheet:
            if row['pitch_type'] == self.name:
                print("The average speed of a " + self.result + " for a "
                    + self.name + " is " + str(self.avg_start_speed()))

p1 = Pitch("CH", "S")
p1.myfunc()

I am receiving this error

NameError: name 'avg_start_speed' is not defined

I'm not sure how to fix it. Thanks for all advice in advance.

CSV sample:

start_speed end_speed   type    pitch_type
92.9    84.1    S   FF
92.8    84.1    S   FF
94.1    85.2    S   FF
91  84  B   FF
75.4    69.6    B   CU
92.9    84.8    S   CH
93.3    85.3    B   FF
89.3    82.4    X   FC
92.1    85  S   CH
2
  • Please show a traceback and fix either your question or your title. They don't match. Commented May 17, 2019 at 2:34
  • 1
    Use self.avg_start_speed() instead. Commented May 17, 2019 at 2:34

1 Answer 1

1

Some issues in your code .

  • You are missing a self argument in def avg_start_speed(): assuming you want to use it as a class method. (I see you using self inside the function definition as well). So it will be def avg_start_speed(self):

  • You also want to call the function avg_start_speed() using self in myfunc like self.avg_start_speed()

  • You also define spreadsheet outside the class. Why not define it inside the class, maybe within __init__ and use it?

  • You don't declare startspeed variable within avg_start_speed() function as well

Always remember, for class methods, the first argument is always self, and you call them inside other class methods within the class using class.func()

Taking those changes to effect, the code will look like

import csv

class Pitch:
    def __init__(self, name, result, spreadsheet):
        self.spreadsheet = spreadsheet
        self.name = name
        self.result = result

    def avg_start_speed(self):
        #Calculate average speed and return
        startspeed = []
        for row in self.spreadsheet:
            if row['pitch_type'] == self.name and row['type'] == self.result:
                startspeed.append(float(row['start_speed']))
        return sum(startspeed) / len(startspeed)


    def myfunc(self):

        #Call avg_start_speed here and print it using string.format
        avg_start_speed = self.avg_start_speed()
        print("The average speed of a {} for a {} is {}".format(self.result,self.name ,
            avg_start_speed))

#Open pitches.csv outside the class
with open('pitches.csv') as fh:
    #Open the csv as a dict and pass it as an argument to Pitch
    spreadsheet = csv.DictReader(fh)
    p1 = Pitch("CH", "S", spreadsheet)
    p1.myfunc()

So if the pitches.csv looks like

start_speed,end_speed,type,pitch_type
92.9,84.1,S,CH
94.1,85.2,S,CH

The output will be

The average speed of a S for a CH is 93.5
Sign up to request clarification or add additional context in comments.

12 Comments

Ok, I made your changes however, im getting this traceback message: Traceback (most recent call last): File "C:\Users\jmmci\OneDrive\Documents", line 32, in <module> p1.myfunc() File "C:\Users\jmmci\OneDrive\Documents", line 29, in myfunc + self.name + " is " + str(self.avg_start_speed())) File "C:\Users\jmmci\OneDrive\Documents", line 21, in avg_start_speed startspeed.append(row['start_speed']) KeyError: 'start_speed' Any ideas? @Devesh
Perhaps you are not reading the csv correctly, or there is no key called start_speed in your dictionary. Can you double check. Also please add the contents your csv in the question @Sam. Also add your updated class according to the suggestion I made at the end of the question too
Ok I posted the updated script, however I'm still not sure what you mean by updating the question, what should I change it to? Also, you did mention moving my spreadsheet inside the class, do i just put it before self.name = name? @Devesh
Add the contents of pitches.csv to the question. Yes move those two lines in the init function and do self.spreadsheet @Sam
Okay I have updated the code, it should work now @Sam
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.