使用Python查找某些数字的平均值

时间:2012-10-11 00:39:45

标签: python while-loop except

我正在使用Python来做一个问题,比如不断要求用户输入数字。如果没有,程序应计算这些数字的平均值。看起来我的程序无法从第二个while循环中逃脱,而“except”仍然是错误的。这是我的计划:

count =0
total=0
ask=input ("Do you want to enter a number? (Y/N)")
while ask=="Y":
    numbers=float(input("Enter number"))
    count= count+1
    total=total+numbers
    con_ask=input ("Do you want to continue entering a number? (Y/N)")
    if con_ask=="Y":
        numbers=float(input("Enter number"))
        count=count+1
        total=total+numbers
    elif con_ask=="N":
        print ("The average of", count, "numbers is", total/count)
except :
    print ("Zero Division Occured. Average cannot be calculated")

7 个答案:

答案 0 :(得分:1)

我的计算平均数版本:

count = 0
total = 0
ask = raw_input("Do you want to enter a number? (Y/N)")
try:
    while ask == "Y":
        numbers = float(raw_input("Enter number"))
        count = count + 1
        total = total + numbers
        con_ask = raw_input("Do you want to continue entering a number? (Y/N)")
        if con_ask == "Y":
            continue
        elif con_ask == "N":
            print "The average of", count, "numbers is", total / count
            break
except:
    print "Zero Division Occured. Average cannot be calculated"

答案 1 :(得分:1)

另一种方法:

numbers = []
ask = raw_input("Do you want to enter a number? (Y/N) ")
while ask == "Y":
   numbers.append(float(raw_input("Enter number ")))
   ask = raw_input("Do you want to continue entering a number? (Y/N) ")

if numbers:
    avg = sum(numbers,0.0) / len(numbers)
    print "The average of {0} numbers is {1}".format(len(numbers),avg)
else:
    print "You didn't enter any numbers"

答案 2 :(得分:0)

您似乎在ask == "Y"时循环,但稍后设置变量con_ask。 你可以重用ask吗?

此外,实现此目的的另一种方法可能是首先使用输入中的所有数字填充数组,然后平均值变为:

sum(numbers) / len(numbers)

答案 3 :(得分:0)

这里只有一个while循环。您可以重用ask,以便在每次循环迭代后进行测试。

ask=input ("Do you want to continue entering a number? (Y/N)")

答案 4 :(得分:0)

如果您想要一个简单的程序来计算某个数字的平均值,您可以查看Python Cookbook

答案 5 :(得分:0)

from sys import argv

t=0
c=0
ans=raw_input("Enetr the choice")

while ans=="Y" or ans=="y":
    a=float(raw_input("Value\t"))
    t=t+a
    c=c+1
    print  "-------------------------------------------"
    print "avarage %f\n" %(t/c)
    ask=raw_input("do you wanna continue \t")
    if ask=="y" or ask=="y":
        continue
    else:
        print "Not wanna more inputs\n"
        break
        print "---------- END ----------------------------"

答案 6 :(得分:0)

如果您知道需要输入多少数字

我的答案是:

l=[]

a=int(input('How much numbers you need to enter:'))

for x in range(a):

    s=float(input())
    l.append(s)
print(sum(l)/a)

如果您不知道需要输入多少数字

l=[]

a=input('If you want to enter a number then enter a Y if you dont't enter N:')

while a=='Y':
     s=float(input())
     l.append(s)
     a=input('If you want to enter a number then enter a Y if you dont't enter N:')
print(sum(l)/len(l))