【问题标题】:How do I count the number of entries in a python code using while loops?如何使用while循环计算python代码中的条目数?
【发布时间】:2013-02-20 17:13:31
【问题描述】:

我正在为我的 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 

【问题讨论】:

  • 更正你的python缩进!
  • (第一个问题很好,顺便说一句——欢迎来到 Stack Overflow)

标签: python input for-loop while-loop


【解决方案1】:

每次读取输入 total += int(entry) 时,应立即增加一个变量。

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

确保while 循环中所有语句的缩进级别相同。您的帖子(如最初所写)没有反映任何缩进。

【讨论】:

  • 哇,原来如此简单。我肯定是想多了。感谢您的所有帮助,我一定会修复缩进!
  • 很高兴我能帮上忙。一些友好的编辑器似乎已经为您修复了这篇文章中的缩进,但只有您可以在您的计算机上修复代码中的缩进!
  • 很高兴我发现了这个网站。我是软件工程专业的一年级学生,我觉得这不会是我第一次在这里发帖!这么酷,乐于助人的地方!
  • 我希望你喜欢这里!通过选中答案分数旁边的复选标记,请务必选择其中一个问题作为该问题的“已接受答案”。
【解决方案2】:

正如@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)

【讨论】:

  • 他被禁止使用 len() 函数,但根据分配说明。
  • @BlackVegetable 啊,应该更彻底地阅读 OP。不过,我会将其留作参考。
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
相关资源
最近更新 更多