2013-03-06 49 views
3

我正在为我的入门级python编程课做一个家庭作业任务,而且我遇到了一个问题。指令如下:如何计算使用while循环的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 
+1

纠正你的python缩进! – Rubens 2013-03-06 03:30:49

+1

(好的第一个问题,顺便说一句 - 欢迎来到堆栈溢出) – BlackVegetable 2013-03-06 03:34:42

回答

3

每当您读取输入total += int(entry),紧接着您应该增加一个变量。

num += 1就是在您将其初始化为0之后所需的全部内容。

确保您的缩进级别对于while循环中的所有语句都是相同的。您的文章(原文)并未反映任何缩进。

+0

哇,那太简单了。我绝对是在推翻它。感谢您的帮助,我将确定修改缩进! – 2013-03-06 03:36:20

+0

很高兴我能帮到你。一些友好的编辑似乎已经修复了您在这篇文章中的缩进,但只有您可以在您的计算机上修复代码中的缩进! – BlackVegetable 2013-03-06 03:37:18

+0

Sooo很高兴我发现了这个网站。我是软件工程专业的第一年,我觉得这不会是我第一次在这里发布!这样一个很酷,有用的地方! – 2013-03-06 03:48:10

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) 
+0

尽管如此,他被禁止使用len()函数。 – BlackVegetable 2013-03-06 03:35:27

+1

@BlackVegetable啊,应该更彻底地阅读OP。不过,我会留下这个参考。 – 2013-03-06 03:37:57