如何用while循环计算Python代码中的条目数量?

3 投票
2 回答
22070 浏览
提问于 2025-04-17 18:05

我正在做一个关于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 

2 个回答

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)
3

每次你读取一个输入的时候,比如用 total += int(entry) 这行代码,之后你应该立刻把一个变量加一。

只需要用 num += 1 这行代码就可以了,前提是你在其他地方把这个变量初始化为0。

确保在 while 循环里的所有语句缩进级别是一样的。你原来的帖子里没有显示任何缩进。

撰写回答