In: Computer Science
Write a python program that will ask the user to enter as many positive and negative numbers and this process will only stop when the last number entered is -999. Use a while loop for this purpose. Your program should compute three sums; the sum of all numbers, sum of all positive numbers, and the sum of all negative numbers and display them. It should also display the count of all numbers, count of all positive numbers, and count of all negative numbers. Finally, it should compute and display the average of all numbers, average of all positive numbers, and average of all negative numbers.
Python program for the above question:
tot_sum=0
pos_sum=0
neg_sum=0
tot_cnt=0
pos_cnt=0
neg_cnt=0
while(1):
x= int(input('Enter a number or enter -999 to exit:'))
if(x==-999):
if(tot_cnt!=0):
tot_avg = tot_sum / tot_cnt
else:
tot_avg= "Not defined as total count is zero."
if(pos_cnt!=0):
pos_avg = pos_sum / pos_cnt
else:
pos_avg = "Not defined as postive count is zero."
if(neg_cnt!=0):
neg_avg = neg_sum / neg_cnt
else:
neg_avg = "Not defined as negative count is zero."
print("The sum of all the numbers is: ",tot_sum)
print("The sum of all positive numbers is: ",pos_sum)
print("The sum of all negative numbers is: ",neg_sum)
print("The count of all the numbers is: ",tot_cnt)
print("The count of all positive numbers is: ",pos_cnt)
print("The count of all negative numbers is: ",neg_cnt)
print("The average of all the numbers is: ",tot_avg)
print("The average of all positive numbers is: ",pos_avg)
print("The average of all negative numbers is: ",neg_avg)
exit(0)
else:
tot_sum= tot_sum + x
tot_cnt=tot_cnt+1
if(x>0):
pos_cnt=pos_cnt+1
pos_sum=pos_sum+x
if(x<0):
neg_cnt=neg_cnt+1
neg_sum=neg_sum+x
EXPLANATION:
I have taken the help of a while loop with true condition and whenever the input value is -999 then it prints all the details and exit. If the number is other than -999 then i am checking for whether it is positive or negative and adding to that sum ,increasing the respective counts and finally counting the average, I have include not defined statements so to avoid division by zero.
NOTE: In case of any doubt/problem regarding any part of the code or explanation please feel free to let me know in the comment section so that i can solve your doubt/problem as soon as possible and after reading the solution kindly, please UPVOTE.