追加Python返回而不是覆盖

时间:2014-06-14 06:07:23

标签: python function return

我正在教自己Python并编写一个简单的GPA计算器。除了大学Java课程之外,我之前的编程经验很少,所以请耐心等待我的代码。

前提是,代码会询问您是否要将课程添加到列表中。如果这样做,它会运行一个函数,询问您的类名。每次添加一个类时,它都会询问您是否要添加另一个类。如果你不这样做,它会吐出你添加的课程列表,然后要求你输入成绩。我没有完成评分部分。我认为这不会太难。

问题是你可以添加一堆类,它只会吐出你输入的最后一个。我假设问题出在askAgain():classList = addClasses(),因为它会一直覆盖,但我不确定如何避免全局变量(因为它们很糟糕?)并且仍然不能覆盖它自己。当我试图弄清楚如何调用一次以初始化它而不是再次运行时,我似乎画了一个空白。我还读到条件变量很糟糕,所以我不确定这里的最佳做法是什么。感谢

def main():
    askAgain()
    return 0


def askAgain():

    while True:
        addOrNot = raw_input("Add a class? [y/n]: ")
        if addOrNot == "Y" or addOrNot == "y":
            classList = addClasses() #This is probably where my issue is.
        else:
            try:
                editClassGradeSelection = mainMenu(classList)
                addGrades(editClassGradeSelection, classList)
            except:
                print("Hey you didn't add any classes yet.")    

def addClasses():
    try:
        if classList in locals():
            print("debug msg - classList exists")
    except:
        classList = []

    classList.append(raw_input("Add class to the list: "))
    return classList


def mainMenu(classList):
        print("Here are the classes you've added: ")
        counter = 0
        for classes in classList:
            print((str(counter+1)) + ". " + (str(classList[counter])) + "\n")
            counter = counter + 1
        while True:
            editGrade = raw_input("Enter the number for the class grade to edit: ")
            if int(editGrade) > len(classList) or int(editGrade) < 1:
                print("Enter a proper number in the range listed.")
            else:
                break

        return editGrade


def addGrades(editClassGradeSelection, classList):
    print("debug stuff for now: ")
    print((str(editClassGradeSelection)))
    print((str(classList[:])))


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

虽然此代码段确保定义了classlist

try:
    if classList in locals():
        print("debug msg - classList exists")
except:
    classList = []

classlist是一个局部变量,因此每次运行该函数时,classlist都将为[],这可能解释了为什么您不能显示多个。每次调用此行时,您为其分配的classlist都会重新分配给classlistaddClasses范围)的一个元素:

        classList = addClasses() #This is probably where my issue is.