Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 350
nedarb Avatar asked Nov 30 '25 19:11

nedarb


1 Answers

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.

like image 159
Aleph Aleph Avatar answered Dec 02 '25 08:12

Aleph Aleph