這是我到目前爲止,我正在創建一個程序,要求用戶輸入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()
請修復您的縮進 – jramirez
對我來說不算太遠,但Python 3中的'input'總是返回一個字符串。您需要在比較0之前調用「int」,從而允許用戶輸入除數字以外的其他內容。 –
當我在閒置時運行它會給我一個「預期的縮進塊」錯誤sum_positive – user32152