如何添加定义模块?

时间:2019-03-08 00:33:42

标签: python

我正在完成老师给我的任务,它要求一个模块化程序,因此我尝试创建一些def模块,但是我不知道如何在它们之间传递参数。

这是到目前为止的代码。 (抱歉,我不知道如何使它更整洁。)

import string

def Datawrite ():
    forename = []
    surname = []
    distance = []
    data = open("members.txt","r")
    for line in data:
        value = line.split(',')
        forename.append(value[0])
        surname.append(value[1])
        distance.append(value[2])
    data.close()

def FarthestWalker(distance):
    farthest_walk = distance[0]
    for counter in range(len(distance)):
        if float(distance[counter]) >= float(farthest_walk):
            farthest_walk = distance[counter]
            farthest_walk = float(farthest_walk)
            Calcandstore()

def Calcandstore(forename,surname,distance,farthest_walk):
    Results = open("Results.txt","w+")
    Results.write("The prize winnning memberes are:\n")
    seventy = 0.7*farthest_walk
    Winning = []
    for count in range(len(distance)):
        if float(distance[count]) >= float(seventy):
            Winning.append([count])
            for count in range(len(Winning)):
                Results.write(forename[count]+":")
                Results.write(surname[count]+":")
                Results.write(distance[count])
            Results.close()

Datawrite()
FarthestWalker(distance)
Calcandstore(forename,surname,distance,farthest_walk)

当我运行代码时,它将返回此值。

Traceback (most recent call last):
  File "E:\Assignment\Test.py", line 58, in <module>
    FarthestWalker(distance)
  File "E:\Assignment\Test.py", line 29, in FarthestWalker
    farthest_walk = distance[0]
IndexError: list index out of range

我已经对此进行了几天的修改,但无法解决问题。

1 个答案:

答案 0 :(得分:0)

以下是一些问题: 1)Datawrite不返回任何内容,因此您正在建立的列表在以太中丢失。 2)您以从未初始化的距离呼叫FarthestWalker。 3)您使用未初始化的值调用Calcandstore

要从函数传递值,您需要返回值并声明它们。例如:

def make_cat():
    return 'Cat'

def print_animal(animal):
    print(animal)

c = make_cat()
print_animal(c)