3

在我的代码中,项目 percentgrade 没有在 for 循环的每次迭代中附加到列表 lnpercentgrade ,但我不知道为什么。当我尝试对 lnpercentgrade 中的项目求和时(在代码末尾),我返回 0,因为 lnpercentgrade 是 empy。我将 lnpercentgrades 声明为 maininput() 函数之外的全局变量,因为否则当我尝试求和(lnpercentgrades)时,在代码的底部,我会返回“lnpercentgrades not defined”。

我猜 lnpercentgrades 没有在 maininput() 函数中以某种方式被修改,即使我确定我在 .append 函数之前输入正确。

我真正想做的是将总和(lnpercentgrades)与 100 匹配,但是当我输入 5 个项目的值都为 20 时,总和是 0 而不是 100。

重要的行用箭头标记<<<<<<<<<<<<<<<<<<<<

lnpercentgrades = []   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
def maininput():
    numtests = int(input("Enter # of tests:"))
    numassign = int(input("Enter # of assignments:"))
    numquizzes = int(input("Enter # of quizzes:"))
    numlabs = int(input("Enter # of labs:"))

    l = [numtests, numassign, numquizzes, numlabs]
    ln = ["test", "assignments", "quizzes", "labs"]
    lnpercentgrades = [] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    testwavg = None
    numassignwavg = None
    numquizzeswavg = None
    numlabswavg = None
    numfinalwavg = None

    lnwavg = [testwavg, numassignwavg, numquizzeswavg, numlabswavg]
    print(l[0])
    print("Is there a separately weighted final?")
    yn = int(input("Enter 1 for yes. 2 for no:"))
    while (yn > 2 or yn < 1):
        yn = int(input("Enter 1 for yes. 2 for no, please:"))

    n = 4 
    if yn == 1:
        final = 1
        l.append(final)
        ln.append("final")
        lnwavg.append(numfinalwavg)
        n = 5


    for i in range (n):
        if l[i] > 0:
            print("Enter % of total grade of",ln[i],":") 
            percentgrade = float(input("")) 
            print("you inputed:", percentgrade)
            lnpercentgrades.append(percentgrade) <<<<<<<<<<<<<<<<<<<<<<
            percentgrade = percentgrade*.01 


            varscoreslist = []
            for x in range(l[i]):
                print("Enter score of", ln[i], x+1,"as a fraction:")
                from fractions import Fraction
                inputfrac = input("")
                varscore = float(sum(Fraction(s) for s in inputfrac.split())) 
                #the above converts fractional inputs to decimals
                varscoreslist.append(varscore)

            if ln[i] == "labs":
                score = sum(varscoreslist)
            else:
                sumscores = sum(varscoreslist)
                score = sumscores/l[i]

            lnwavg[i] = score*percentgrade

maininput()
print(lnpercentgrades)
print("sum of percent of grades", sum(lnpercentgrades)) <<<<<<<<<<<<<<<

if float(sum(lnpercentgrades)) != 100:  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    print("Sorry, the grade percent of each item enter did not sum to 100:")
    print("Program will rerun.")
    input("")
    maininput()

coursegrade = sum(lnwavg)
print("Your course grade is:", coursegrade)

input("")
4

1 回答 1

8

乍一看,您可能有范围界定问题。您正在修改函数内部的列表,但请记住这是列表的本地副本。尽管您在外部范围内声明它,但您并没有在它前面加上global,这意味着它会创建一个函数本地副本,执行其业务然后退出,根本不会影响“主”列表。

我建议修改您的函数以返回您想要的列表,以便您可以按预期使用它们。这是一个基本示例:

def MyFunc():
    l1 = ['my', 'first', 'list']
    l2 = ['another', 'list']
    return l1, l2

main_list, second_list = MyFunc()

print(main_list)
print(second_list)

这将输出:

['my', 'first', 'list']
['another', 'list']

如果您真的想将变量保留在外部范围内,则必须global在函数内部为其开头(尽管我可能会使用第一种方法):

main_list = []
second_list = []

def MyFunc():
    global main_list
    global second_list
    main_list = ['more', 'good', 'stuff']
    second_list = ['another', 'list']


MyFunc()

print(main_list) # ['more', 'good', 'stuff']
print(second_list) # ['another', 'list']
于 2012-11-20T02:30:29.773 回答