简体   繁体   中英

How do I write this function in Python?

*I'm a Beginner... My friend tried to help me a bit with this but I can't seem to solve it. I'm not really sure what to do so any help would be greatly appreciated.I get the following error in averageMPG,"name stats city is parameter and global".I also wasn't really sure how to write both functions in my readData function as you can see. The problem is in the picture. I haven't succeeded in part b so I haven't moved on,

def readData(carmodelData_city):

    global stats_city,stats_hwy
    infile=open("carModelData_city", 'r')
    stats_city=[]
    for s in infile.read.split():
        stats.append(float(s))
        return stats_city


def read_Data(carmodelData_hwy):
    global stats_city,stats_hwy
    infile=open("carModelData_hwy", 'r')
    stats_hwy=[]
    for s in infile.read.split():
        stats.append(float(s))
        return stats_hwy        


def averageMPG(stats_city, stats_hwy):
       global stats_city,stats_hwy  
       totals=sum(stats_city)
       length=len(stats_city)
       avg1=totals/length
       print("The averge mpg city is", avg1)
       totals1=sum(stats_hwy)
       length1=len(stats_hwy)
       avg2=totals/length
       print("The average mpg highway is", avg2)
       average=(avg1+avg2)/2
       print("The combined averge mpg is", average)


def main():
global stats_city,stats_hwy
stats_city=readData("carModelData_city", "r")
stats_hwy=read_Data("carModelData_hwy", "r")



[enter image description here][1]main()

You named a function parameter stats_city , and also declared it a global value. Those two things are incompatible.

AFAICT, none of your code actually requires anything to be global in the first place, so stop declaring everything global , and you should be fine.

Well, fine on that specific error anyway. The massive overuse of global here feels an awful lot like cargo cult programming, and you have many other problems (eg infile.read.split() is going to try to split the read method of the file; you forgot parens, so it's not actually calling read to get data back). You're also returning at the end of the first iteration of each loop, when I suspect you want to finish the loops and return the accumulated values. You need to learn a lot more of the basics here; please talk to a professor or a tutor.

Also, your "stats.append()" calls should probably be "stats_city.append" in the first function and "stats_hwy.append" in the second. You will return after one iteration in each function unless you adjust your idents on the return call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM