python - 使用Python求一些数字的平均值

标签 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")

最佳答案

我的计算平均数的版本:

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"

关于python - 使用Python求一些数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12830540/

相关文章:

c++ - 在 C++ 的 while 循环中使用 pow() 函数

python:异常流程:捕获后继续向下捕获 block ?

python - 访问时自动创建(并保留)一个对象

python - flask 和 WTForms : DatePicker Widget to display a date

c++ - 使用 while 循环和 for 循环排序?

angular - 如何删除 FormArray 的所有元素但一个特定索引?

c# - 使用 IEnumerable.Except

python - 无法使用 python 连接到 TOR

python - 关闭BeautifulSoup困惑编码置信度输出

python - 运行程序一分钟然后暂停一分钟的最简单方法是什么