0

试图显示数组中有多少值高于计算的平均值的计数,当我出于某种原因运行我的代码时,它会跳过计数器循环以计算高于平均值的学生年龄:我加载了具有 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
4

4 回答 4

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
于 2013-11-14T17:35:59.437 回答
0

“另外,如果我想退出循环并且不在 if/else 中的 else 上放置任何东西,如果你想在 else 上留出空白空间,那么你能放什么,所以没有任何变化?”

你可以写 pass 在其他部分什么都不做。

可能的解决方案是:

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])
于 2013-11-14T17:38:11.017 回答
0
  1. 要汇总所有列表元素,您可以使用内置sum()函数。
  2. 你循环g,但你永远不会g在循环中改变。换句话说,g始终等于 0,并且while循环永远不会结束。
  3. 您可以使用列表推导来更轻松地编写此内容。例如:

print len(age for age in st_age if age > average)

于 2013-11-14T17:33:09.750 回答
0

你没有义务放置一个else块。如果列表元素满足您的条件,只需添加 1 count,并且不要忘记g在每种情况下递增,因为您实际上不是遍历列表,而是始终引用其第一个元素。

我的提议:

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
于 2013-11-14T17:27:55.590 回答