有关name未定义的问题
def main():credit,grade = getInfor()
finalscore = judge(credit,grade)
def getInfor():
a = eval(input('请输入课程学分'))
b = eval(input('请输入成绩'))
return a,b
def judge(a,b):
score = 0
if b == "A":
score = 4
elif b == "B":
score = 3
elif b == "C":
score = 2
else:
score = 1
score = b*a
return score
main()
错误显示为:NameError: name 'A' is not defined
想知道错误的原因,谢谢各位大神 在你的代码是并没有A的变量,估计是不是编辑器其它部分的代码没有清除。if b == "A":
if b == "A":
score = 4
elif b == "B":
score = 3
elif b == "C":
score = 2
else:
score = 1
并且这段代码不执行,因为你传入的b是数值型。并没有''ABC'类的字符串' eval使用的问题,你用input的结果作为eval的实参,如果是数字,可以正确实现,
但是如果是字符串,那得到的将是一个以这个字符串为名字的变量,而你并没有对这个变量初始化
举个例子:
比如,你输入了 A
那么等价于 a = eval('A')
此时 A 被当作一个变量,赋值给a,而A并没有被定义,所以报错
还有一个小错误,最后算score应该是score *= a
而不是score= b * a
修改建议:
a = input('请输入课程学分')
最后
score *= a 非常感谢
页:
[1]