难以弄清楚我的代码中出了什么问题

时间:2016-03-10 14:35:31

标签: python

当我尝试运行一段代码时,我收到了错误,我不确定原因。我的错误信息是:

 Traceback (most recent call last):
  File "\\srv-005\student2011documents$\hbyrne11\My Documents\GCSE Computing\controlled assesment(Python)\controlled assessment VM\CA Harry.py", line 130, in <module>
    print (cl)
NameError: name 'cl' is not defined" 

我的代码如下:

Score = 10
Class = Class + ".txt"
file = open(Class,'a')
Name = (name)
file.write(str(Name + ":")) 
file.write(str(Score))
file.write("\n")
file.close()



if Class == "1":
    with open("1.txt", 'r') as file:
        cl = {}
        for record in file:
            n, s = record.split(':')
            try:
                cl[n].append(int(s))
            except KeyError:
                cl[n] = [int(s),]
    file.close()

if Class == "2":
    with open("2.txt", 'r') as file:
        cl = {}
        for record in file:
            n, s = record.split(':')
            try:
                cl[n].append(int(s))
            except KeyError:
                cl[n] = [int(s),]
    file.close()


if Class == "3":
    with open("3.txt", 'r') as file:
        cl = {}
        for record in file:
            n, s = record.split(':')
            try:
                cl[n].append(int(s))
            except KeyError:
                cl[n] = [int(s),]
    file.close()

print ("-------------------------")
print ("Class"+" "+Class + "'s "+"results")
print (cl) 
print ("-------------------------")
alphabetically = sorted(cl.items(), key = lambda t: t[0])
print ("Sorted Alphabetically:")
print(" /// ".join(["{}: {}".format(k, v) for k, v in alphabetically]))  
print ("-------------------------")
print ("Sorted Highest to Lowest:")
valuesort = sorted(cl.items(), key=(lambda t:max(t[1])), reverse=True)
print(" /// ".join(["{}: {}".format(k, v) for k, v in valuesort]))  
print ("-------------------------")
print ("Average by Highest to Lowest:")
averagesort = sorted([(k,sum(v)/len(v)) for k,v in cl.items()], key=lambda x: x[1], reverse=True)
print(" /// ".join(["{}: {}".format(k, v) for k, v in averagesort]))  
print ("-------------------------")    

3 个答案:

答案 0 :(得分:1)

编辑:我没有看到其他两个答案所说的关于你如何改变Class以使它永远不会等于1,2,3。

将if子句改为

if Class == "1.txt":
    #code
elif Class == "2.txt":
    #code
elif Class == "3.txt":
    #code
else:
    #code to deal with Class not being what you think it should be.
    # perhaps something like
    raise RuntimeError("Class is {}.\n".format(Class))

应该解决问题。我认为你应该将第二个和第三个if语句更改为elif。当只有其中一个适用时,让口译员检查所有这三个是没有意义的。

答案 1 :(得分:0)

根据您发布的第二行代码,您的Class变量将以“.txt”结尾,因此这三种情况都不适用,变量cl将永远不会被分配。这就是为什么在尝试打印它时无法在范围内找到它并引发NameError

答案 2 :(得分:0)

您收到的错误是,没有定义名称cl的变量。我认为这是因为您要在cl语句中定义if,但是您使用 something.txt 覆盖变量Class,以便Class永远不会是“1”“2”“3”之一,永远不会达到if语句。

希望这有帮助!