I need to write a program where the user inputs 2 numbers and then it gives the sum of all odd numbers in that range plus the 2 numbers that the user entered. I've searched around a lot but haven't found anything that includes the limits. So far I have:
x=int(input('Enter first number: '))
y=int(input('Enter second number: '))
def SumOdds(x,y):
count=0
for i in range(x,y):
if (int(i%2==1)):
count=count+i
print(count)
SumOdds(x,y)
This gives the sum of the odds, but doesn't include the limits. For example, say I put in 10 and 20. This gives me 75, but it needs to add on the 10 and 20 to make it 105. I'm sure this is a simple fix, but I'm very new to Python so any help would be appreciated. Thanks!
So all you're missing is the addition of your two numbers when you finish your for loop. Try this:
x=int(input('Enter first number: '))
y=int(input('Enter second number: '))
def SumOdds(x,y+1):
count= x + y #notice instead of 0, it's the sum now!
for i in range(x,y):
if(i == x or i == y):
pass
elif (int(i%2==1)):
count=count+i
print(count)
SumOdds(x,y)
Edit: as per your comment, you won't want to add your limits twice if they're odd. The y+1 ensures you're capturing the whole range, and the check for i == x or i == y skips those values in the range, since we've already added them at the start.
Just check the bounds separately.
x=int(input('Enter first number: '))
y=int(input('Enter second number: '))
def SumOdds(x,y):
count=0
for i in range(x,y):
if (int(i%2==1)):
count=count+i
if(x%2==0):
count= count+x
if(y%2==0):
count= count+7
print(count)
SumOdds(x,y)
The base loop should include any odd limits, so you only have to add the limits if they are odd.
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