我正在使用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/