2013-03-06 47 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