平均公式

问题描述 投票:-1回答:2

我正在为学校创建下面的代码的分数表:

Sub1 = input ('Enter Marks of English: ')
Sub2 = input ('Enter Marks of Urdu: ')
Sub3 = input ('Enter Marks of Science: ')
Sub4 = input ('Enter Marks of Maths: ')
Sub5 = input ('Enter Marks of Islamiat: ')
avg = (Sub1+Sub2+Sub3+Sub4+Sub5)
Sub1 = int(Sub1)
Sub2 = int(Sub2)
Sub3 = int(Sub3)
Sub4 = int(Sub4)
Sub5 = int(Sub5)
if avg >90 or (avg <80):
    print("Grade: A")
elif avg > 79 or (avg < 61):
    print("Grade: B")
elif avg > 60 or (avg < 40):
    print("Grade: C")
elif avg > 40 or (avg < 39):
    print("Grade: D")
else:
    print("Grade: F")

但是,按照平均法计算时却出现错误

TypeError
Traceback (most recent call last)
<ipython-input-25-68aee6e8df0f> in <module>
     12 Sub5 = int(Sub5)
     13
---> 14 if avg >90 or (avg <80):
     15     print("Grade: A")
     16 elif avg > 79 or (avg < 61):
TypeError: '>' not supported between instances of 'str' and 'int'

请明天帮忙解决,必须提交我的作业。

python python-3.7
2个回答
1
投票

当您读取用户输入时,您的变量为str。因此,您需要在添加之前将Subn变量转换为int。替换:

avg = (Sub1+Sub2+Sub3+Sub4+Sub5)
Sub1 = int(Sub1)
Sub2 = int(Sub2)
Sub3 = int(Sub3)
Sub4 = int(Sub4)
Sub5 = int(Sub5)

for

Sub1 = int(Sub1)
Sub2 = int(Sub2)
Sub3 = int(Sub3)
Sub4 = int(Sub4)
Sub5 = int(Sub5)
avg = (Sub1+Sub2+Sub3+Sub4+Sub5)

0
投票

您具有将输入从字符串转换为整数的代码,这是避免TypeError所必需的。但是您要在此转换之前计算avg,所以avg是一个字符串。解决的办法是移线

avg = (Sub1+Sub2+Sub3+Sub4+Sub5)

将这些变量转换为int之后的。

还要注意,该公式给出的是总和,而不是平均值。


-1
投票

只是改变

avg = (Sub1+Sub2+Sub3+Sub4+Sub5)

to

avg = eval(Sub1+Sub2+Sub3+Sub4+Sub5) // 5
© www.soinside.com 2019 - 2024. All rights reserved.