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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With