How to Sum Negative(-), Positive (+) Even/Odd numbers in Python


In this example we will show how to calculate the sum of negative numbers, positive even numbers, positive odd numbers in a given data list with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = input("Please input a list of numbers (including positive and negative), separed by SPACE: ")
a = n.split()
sum1 = 0
sum2 = 0
sum3 = 0
for i in range(0, len(a)):
    if int(a[i]) > 0:
        if int(a[i]) % 2 == 0:
            sum1 = sum1 + int(a[i])
        else:
            sum2 = sum2 + int(a[i])
    else:
        sum3 = sum3 + int(a[i])
print("The sum of all positive even numbers: ", sum1)
print("The sum of all positive odd numbers: ", sum2)
print("The sum of all negative numbers: ", sum3)

Output:

Please input a list of numbers (including positive and negative), separed by SPACE: 23 56 -16 36 -13 79
The sum of all positive even numbers: 92
The sum of all positive odd numbers: 102
The sum of all negative numbers: -29
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments