nedarb
nedarb

Reputation: 35

Struggling to get the Sum() function to output one value from a list

olst = []
elst = []

E = int(input("Please enter your first number:  "))
O = int(input("Please enter your second number:  "))
for OS in range(E,O+1):
    if(OS%2!=0):
        olst.append(OS)

for ES in range(E,O+1):
    if(ES%2==0):
        elst.append(ES)

    print("Sum of all odd values is:  ", sum(olst))
    print("Sum of all even values is:  ", sum(elst))

This programs intention is to print the sum of all odd numbers between my two integers as well as the even. This is my current code, I'm fairly new to python and tinkering around, open to any criticism and tips. The main issue I'm having is when I run my program both sum(olst) and sum(elst) output the answer multiple times until they reach the correct and final answer. Get the feeling my process is fundamentally flawed somewhere early on but hoping that's not the case!

Upvotes: 3

Views: 57

Answers (2)

Sheldore
Sheldore

Reputation: 39072

You already got your answer above but since you mentioned you are open to tips, this is to provide you just an alternate solution using list comprehensions:

E = int(input("Please enter your first number:  "))
O = int(input("Please enter your second number:  "))

olst = [i for i in range(E, O+1) if i%2  == 1]  
elst = [i for i in range(E, O+1) if i%2  == 0]  

print("Sum of all odd values is:  ", sum(olst))
print("Sum of all even values is:  ", sum(elst))

Additionally, you can replace the middle two lines of the code by

olst = [i for i in range(E, O+1) if i%2 ]  
elst = [i for i in range(E, O+1) if not i%2]  

Upvotes: 0

Aleph Aleph
Aleph Aleph

Reputation: 5395

The last two lines with the print statements should not be indented - otherwise, they are located within the for loop and executed multiple times:

olst = []
elst = []

E = int(input("Please enter your first number:  "))
O = int(input("Please enter your second number:  "))
for OS in range(E,O+1):
    if(OS%2!=0):
        olst.append(OS)

for ES in range(E,O+1):
    if(ES%2==0):
        elst.append(ES)

print("Sum of all odd values is:  ", sum(olst))
print("Sum of all even values is:  ", sum(elst))

There are also many ways how this code can be optimised (for example, you don't really need the lists elst and olst and can compute the sums in the loop or use comprehensions), but that's a different issue.

Upvotes: 1

Related Questions