Python program to print sum of negative numbers, positive even numbers and positive odd numbers in the list














































Python program to print sum of negative numbers, positive even numbers and positive odd numbers in the list



Description:
  1. We first create an empty list that will collect all number input from the user and store it on the list.
  2. we check if the number is positive or negative.
  3. if the number is negative. we calculate the sum of all negative numbers.
  4. if the number is positive, we find the number which is odd or even and calculates their sum separately.

Program:
input_list=[] #an empty list which will have all the inputs given by user
count_of_neg,count_Of_even,count_of_odd=0,0,0 #these are the three variables separated by comma, each is assigned to a value 0
size_of_list= int(input("Enter the number of elemnts in the list to be inserted ")) # user input the number of values he/she wants in the list
for i in range(size_of_list): # a loop that runs until the size of list
input_list.append(int(input())) #append the values entered by user to the input_list
print("Numbers in list are: ", input_list) #we print the final entered values contained in the list.
#loop below checks the condition if the number in the list is negative or positive. if the number is negative, it creates a separate sum of all negative numbers in the list. if the number is positive, it goes for further checking if the number is odd or even and calculate the sum of all positive odd numbers and negative odd numbers

for j in input_list:
if j<0:
count_of_neg+=j
else:
if j%2==0:
count_Of_even+=j
else:
count_of_odd+=j

# format() built-in function is here to replace all {} braces with the value passed inside format() function
print("sum of negative integers:{}".format(count_of_neg), "sum of positive even numbers:{}".format(count_Of_even), "sum of positive odd number:{}".format(count_of_odd), sep="\n")

Output:

Enter the number of elemnts in the list to be inserted 5
-3
-4
2
4
6
Numbers in list are:  [-3, -4, 2, 4, 6]
sum of negative integers:-7
sum of positive even numbers:12
sum of positive odd number:0

Comments

  • Ankita
    11-Sep-2019 02:13:03 PM
    //Enter Your Comment Here...