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

2024-04-20 15:09:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: ofthetoinputrawfunctionfindtotal
2条回答

你可以一直使用一个迭代计数器,就像@blackplate所说的:

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

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

num += 1就是在其他地方将其初始化为0之后所需要的全部。

确保缩进级别与while循环中的所有语句相同。你的文章(原著)没有反映任何缩进。

相关问题 更多 >