如何在Python中解决未处理的NameError

时间:2016-03-06 20:48:00

标签: python

因此,在运行代码时会生成以下错误。 它表示NameError未被用户代码处理。

错误:

Traceback (most recent call last):
File "D:\3rd sem\Object Oriented Programming\Lab\VS\PythonApplication1\PythonApplication1\PythonApplication1.py", line 50, in <module>
main()
File "D:\3rd sem\Object Oriented Programming\Lab\VS\PythonApplication1\PythonApplication1\PythonApplication1.py", line 10, in main

grade=str(input("Enter the grade: "))
File "<string>", line 1, in <module>
NameError: name 'a' is not defined

代码如下:

classnum=int(input("Enter the num of classes: "))

def main():
totalcredit=0
totalgpa=0

for i in range(1,classnum+1):
    print "class", i
    credit=int(input("Enter the credit: "))
    grade=str(input("Enter the grade: "))
    totalgpa+=coursePoints(credit,grade)
    totalcredit+=credit

totalcourse=classnum 
semestergpa=totalgpa/totalcredit
print("Semester summary")
print("courses taken: ", classnum)
print("credits taken: ", totalcredit)
print("GPA points: ", totalgpa)
print("Semester GPA: ", semestergpa)

def coursePoints(Credit,Grade):
    if Grade == 'A+' or Grade == 'a+':
        return 4*Credit
    elif Grade == 'A' or Grade == 'a':
        return 4*Credit
    elif Grade == 'A-' or Grade == 'a-':
        return 3.67*Credit
    elif Grade == 'B+' or Grade == 'b+':
        return 3.33*Credit
    elif Grade == 'B' or Grade =='b':
        return 3*Credit
    elif Grade == 'B-' or Grade == 'b-':
        return 2.67*Credit
    elif Grade == 'C+' or Grade == 'c+':
        return 2.33*Credit
    elif Grade == 'C' or Grade == 'c':
        return 2*Credit               
    elif Grade == 'C-' or Grade == 'c-':                        
        return 1.67*Credit                
    elif Grade =='D+' or Grade == 'd+':                      
        return 1.33*Credit                
    elif Grade == 'D' or Grade == 'd':                        
        return 1*Credit                      
    elif Grade == 'D-' or Grade == 'd-':                                
        return 0.33*Credit                     
    else:
        return 0

main()

任何人都可以提供解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您似乎使用的是Python 2.x,因此您应该更改

grade=str(input("Enter the grade: "))

grade = raw_input("Enter the grade: ")