编写程序以不断要求用户输入数字,直到用户输入大于100的数字为止。然后打印最后一次输入前的数字的平均值。例如,如果用户输入12,23,9,15,155,则输入终止(因为155> 100)并且您的程序打印平均值12,23,9,15,即14.75。
这是我迄今为止所做的,似乎无法让它正常工作
def average():
inputnum = 0
numlist = []
while inputnum <=100:
inputnum = input("Please input a number: ")
inputnum = float(inputnum)
numlist.append(inputnum)
average = sum(numlist)/len(numlist)
print(average)
答案 0 :(得分:3)
你的程序对我来说很好,但缩进是错误的。它必须是这样的:
def average():
inputnum = 0
numlist = []
while inputnum <=100:
inputnum = input("Please input a number: ")
inputnum = float(inputnum)
numlist.append(inputnum)
average = sum(numlist)/len(numlist)
print(average)
average() # finally call the function
要排除输入的数字大于100,请执行以下操作:
def average():
inputnum = 0
numlist = []
while inputnum <=100:
inputnum = input("Please input a number: ")
inputnum = float(inputnum)
numlist.append(inputnum) if inputnum <=100 else None
average = sum(numlist)/len(numlist)
print(average)
average() # finally call the function
对于Jython:
def average():
inputnum = 0
numlist = []
while inputnum <=100:
inputnum = input("Please input a number: ")
inputnum = float(inputnum)
if inputnum <= 100:
numlist.append(inputnum)
average = sum(numlist)/len(numlist)
print(average)
average() # finally call the function