尝试显示数组中有多少值超过计算平均值的计数,当我运行我的代码时出于某种原因它跳过计数器循环来计算学生年龄超过平均值的数量:我加载数组3个年龄值35,25和50,并且想要显示高于平均值的数量,但它会跳过这个?请协助, 另外,如果我想退出循环并且不在if / else中的else上放任何东西,如果你想在else上留空空间你可以放什么所以什么都没有改变?到目前为止,这是我的代码:
st_age = [0] * 3
for g in range(0,3):
st_age[g] = int(input("Enter student age "))
g = 0
sum = 0
count = 1
count2 = 0
while g < len(st_age):
sum = sum + st_age[g]
g += 1
average = sum / len(st_age) #the average calc.
print "the average is:", average
#starting counter loop here:
g = 0
while g < len(st_age):
if st_age[g] > average:
count = count + 1
else: count = count + 1 # I don't know what to put here, it skips the whole thing
print "the number above the average is:", count
答案 0 :(得分:1)
如果你是初学者,你应该注意不要将函数名用作变量:
age = [3,14,55]
sum_age = 0
count = 1
count2 = 0
g = 0
while g < len(age):
sum_age += age[g]
g += 1
average = sum_age / len(age) #the average calc.
print "The average is:", average
g = 0
while g < len(age):
if age[g] > average:
count = count + 1
g += 1
print "The number above the average is:", count
答案 1 :(得分:0)
您没有义务提出else
阻止。如果列表元素满足您的条件,只需向count
添加1,并且不要忘记在每种情况下都增加g
,因为您实际上并不遍历列表但总是引用其第一个元素。 / p>
我的主张:
for age in st_age: # examine all items in st_age one by one
if age > average:
count += 1
print "the number above the average is:", count
答案 2 :(得分:0)
sum()
函数。g
循环,但您永远不会在周期中更改g
。换句话说,g
总是等于0而while
周期永远不会结束。
print len(age for age in st_age if age > average)
答案 3 :(得分:0)
“另外如果我想退出循环并且不在if / else中的else上放任何东西,如果你想在else上留空空间你可以放什么,所以什么都没有改变?”
你可以写 通过 在其他部分什么都不做。可能的解决方案是:
st_age = [0] * 3
for g in range(0,3):
st_age[g] = int(input("Enter student age "))
average = sum(st_age)/len(st_age)
print "the number above the average is:", sum([1 for eachAge in st_age if eachAge>average])