2013-11-25 187 views
0

這是我到目前爲止,我正在創建一個程序,要求用戶輸入7個數字。這些數字可以是任何數字。最終結果將給出正數,負數和所有數字的平均值,如下所示:產生負數和正數的總和的Python程序?

average positive="" 
average negative="" 
average all="" 


import random 

def main(): 
     sum_positive=0 
     count_positive=0 # number of positive 
     sum_negative=0 
     count_negative=0 # number of negative 

    for i in range (7): 
     n=input("Please, enter number %d: " % i) # will display prompt like "Please, enter   number 1:" 
     print ("number entered: ",n) # this will print the entered number, one of the question 
     if n > 0: 
      count_positive += 1 
      sum_positive = sum_positive + n 
     elif n < 0: 
      count_negative += 1 
      sum_negative = sum_negative + n 
    # loop ends here 
    print("Sum of negative number is :", sum_negative) 
    print("Average negative number is : ", sum_negative*1.0/count_negative) 
    print("Sum of positive number is :", sum_positive) 
    print("Average positive number is : ", sum_positive*1.0/count_positive) 



main() 
+0

請修復您的縮進 – jramirez

+0

對我來說不算太遠,但Python 3中的'input'總是返回一個字符串。您需要在比較0之前調用「int」,從而允許用戶輸入除數字以外的其他內容。 –

+0

當我在閒置時運行它會給我一個「預期的縮進塊」錯誤sum_positive – user32152

回答

0

您可以這樣做。

user_input = [] 
for i in range(7): 
    user_input.append(input("Pleace, enter number %d: " % i)) 

negs = [x for x in user_input if x < 0] 
pos = [x for x in user_input if x > 0] 

print "Sum of neg ", sum(negs) 
print "Avg of neg ", sum(negs)/float(len(negs)) 

print "Sum of pos ", sum(pos) 
print "Avg of pos ", sum(pos)/float(len(negs)) 

print "Sum of all ", sum(user_input) 
print "Avg of all ", sum(user_input)/float(len(user_input)) 
+2

'lambda'的'filter'是一種不贊成的,更好地使用列表解析。 'negs = [x for user_input,如果x <0],或者甚至帶有'(',')'的生成器。 Guido在這裏的一個很好的總結:http://www.artima.com/weblogs/viewpost.jsp?thread=98196 – tamasgal

1

有點整齊&更pythonic的代碼。

numbers = [input("Please, enter number {}: ".format(i+1)) for i in range(7)] 
# will display prompt like "Please, enter number 1:" 
print "numbers entered:", numbers # this will print the entered numbers 

positives = [num for num in numbers if num >= 0] 
negatives = [num for num in numbers if num < 0] 

# loop ends here 
print "Sum of negative numbers is :", sum(negatives) 
print "Average negative number is :", sum(negatives)*1.0/len(negatives) 
print "Sum of positive numbers is :", sum(positives) 
print "Average positive number is :", sum(positives)*1.0/len(positives) 

List Comprehensions比正常for循環更快&是更Python。

sum是一個內置函數,它返回提供的迭代中整數/浮點數的總和。

len是一個內置函數,它返回傳遞給它的列表或迭代的長度。

注 - 在Python v3中print是一個函數。另外,input的行爲類似於raw_input,因此爲了將整數作爲輸入,您應該執行int(input())