我正在为我的python编程入门课做家庭作业,遇到了一个问题。说明如下:
我不确定如何计算输入的数量,如果有人能给我一个好的起点,那就太好了!Modify the find_sum() function so that it prints the average of the values entered. Unlike the average() function from before, we can’t use the len() function to find the length of the sequence; instead, you’ll have to introduce another variable to “count” the values as they are entered.
# 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
你可以一直使用一个迭代计数器,就像@blackplate所说的:
或者,您可以将每个数字添加到列表中,然后打印总和和长度:
每次读取输入
total += int(entry)
时,紧接着应该递增一个变量。num += 1
就是在其他地方将其初始化为0之后所需要的全部。确保缩进级别与
while
循环中的所有语句相同。你的文章(原著)没有反映任何缩进。相关问题 更多 >
编程相关推荐