这是我到目前为止,我正在创建一个程序,要求用户输入7个数字。这些数字可以是任何数字。最终结果将给出正数,负数和所有数字的平均值如下:
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 :(得分:1)
有点整洁&amp;更多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
循环更快&amp;更像是pythonic。
sum
是一个内置函数,它返回所提供的iterables中整数/浮点数的总和。
len
是一个内置函数,它返回列表的长度或传递给它的iterable。
注意 - 在Python v3中print
是一个函数。此外,input
的行为与raw_input
相似,因此要将整数作为输入,您应该int(input())
。
答案 1 :(得分: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))