[英]How do I get the above and below the average in python?
I have 3 GPAs I got the average by summing them and dividing by 3. Now, how can I get what is the GPA that above, below, and equal to the average??我有 3 个 GPA,通过将它们相加并除以 3 得到平均值。现在,我怎样才能得到高于、低于和等于平均值的 GPA?
this is the code so far:这是到目前为止的代码:
GPA1 = 4.28
GPA2 = 3.91
GPA3 = 3.64
sum = GPA1 + GPA2 + GPA3
average = sum / 3
print(average)
I tried If, Elif statements... it doesn't work with me.我试过 If, Elif 语句......它对我不起作用。
Thanks in advance提前致谢
One possible solution for this is:一种可能的解决方案是:
GPA1 = 4.28
GPA2 = 3.91
GPA3 = 3.64
gpas = [GPA1, GPA2, GPA3] # pass everything into a list
average = sum(gpas)/len(gpas) # call it average so you don't override the inbuilt sum function
print(average)
below, above, equal = [], [], []
for gpa in gpas:
if gpa < average:
below.append(gpa)
elif gpa == average:
equal.append(gpa)
else:
above.append(gpa)
print("GPAs below:", below)
print("GPAs equal:", equal)
print("GPAs above:", above)
The key here is to group the GPAs together into something like a list.这里的关键是将 GPA 组合成一个列表。 Then you can iterate over them in a forloop.
然后你可以在 forloop 中迭代它们。 Also, avoid using variable names reserved by Python such as
sum
, because then you cannot use them anymore to get, for example, the sum of a list ( sum(gpas)
).此外,避免使用 Python 保留的变量名称,例如
sum
,因为这样您就无法再使用它们来获取例如列表的总和 ( sum(gpas)
)。
Save the values in a list and run a for loop over to check for the condition.将值保存在列表中并运行 for 循环以检查条件。
gpaList = [GPA1, GPA2, GPA3]
for gpa in gpaList:
if gpa > average:
#do stuff
#for eg. print("Above average", gpa)
else:
#do stuff
#for eg. print("Below or equal to average", gpa)
Your question is a little vague I guess your asking for the process/algorithm你的问题有点含糊,我猜你是在问过程/算法
Try this:尝试这个:
for I in [GPA1,GPA2,GPA3]:
if I>average:
Print ("above average" , I)
elif I==average:
Print ("equal to average" , I)
else:
Print (”below average" , I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.