我正在为我的入门python编程课做一个家庭作业,我遇到了问题。说明是:
修改find_sum()函数,使其打印输入值的平均值。与之前的average()函数不同,我们不能使用len()函数来查找序列的长度;相反,你必须引入另一个变量来“计算”输入的值。
我不确定如何计算输入数量,如果有人能给我一个好的起点,那就太棒了!
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = 0
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
答案 0 :(得分:3)
每当您读取输入total += int(entry)
时,您应立即增加变量。
num += 1
只要你在其他地方初始化为0就可以了。
确保while
循环中所有语句的缩进级别相同。您的帖子(最初写的)没有反映任何缩进。
答案 1 :(得分:0)
你总是可以使用迭代计数器,因为@BlackVegetable说:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total, iterationCount = 0, 0 # multiple assignment
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total += int(entry)
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", total
print "Total numbers:", iterationCount
或者,您可以将每个数字添加到列表中,然后打印总和和长度:
# Finds the total of a sequence of numbers entered by user
def find_sum():
total = []
entry = raw_input("Enter a value, or q to quit: ")
while entry != "q":
iterationCount += 1
total.append(int(entry))
entry = raw_input("Enter a value, or q to quit: ")
print "The total is", sum(total)
print "Total numbers:", len(total)