偶数和奇数之和包括超出范围的数字,如果不是偶数或奇数

时间:2019-02-12 22:12:58

标签: python python-3.x sum

所以这是我学习计算机科学的第一个学期,目前正在学习Python。我的任务是创建一个程序,以显示您选择的整数之间的奇数和偶数之和。它几乎可以工作,除了它添加了定义为范围的数字,而不仅仅是其中的几率或偶数。有人可以指出我做错了吗?我已经在这个问题上停留了一段时间。感谢您的帮助!

我已经定义了范围,并使用求和函数来求和,但是包含了我用于范围的值。

enter code here
print("Welcome to my Odd/Even sum generator.")
print("This program will show you the sum of all even and odd numbers between two integers of your choice.")
Num1 = int(input("What is your first, lower integer?"))
Num2 = int(input("What is your second, higher integer?"))


def sum_even(Num1, Num2):
    count1 = 0
    for i in range(Num1, Num2+1):
        if(i % 2 == 0):
            count1 += i
    return count1

def SumOdds(Num1,Num2):
  count2= Num1 + Num2 
  for i in range(Num1,Num2+1):
     if(i == Num1 or i == Num2):
         pass
     elif (int(i%2==1)):
        count2=count2+i

  print("The sum of the odd numbers is",(count2),".")
SumOdds(Num1,Num2)
print("The sum of the even numbers is",(sum_even(Num1, Num2)),".")

仅当这些范围值适用于奇数/偶数总和时,我希望它添加范围值。假设我输入的范围是5到25。我希望将范围值包括在OddSum的总和中,而不是我的EvenSum的总和。

2 个答案:

答案 0 :(得分:0)

您的问题是您已将以下代码放入SumOdds中。

for i in range(Num1,Num2+1):
     if(i == Num1 or i == Num2):
         pass

这会跳过第一个和最后一个数字,但是如果将其移至sum_evens,则您的代码应该可以按预期工作。

答案 1 :(得分:0)

您的代码看起来不错,所做的更改将对您有所帮助:

def SumOdds(Num1,Num2):
    count2 = 0 # here ur adding NUM1+NUM2 by defualt initial it must be zero
    for i in range(Num1,Num2+1):
        if(i == Num1 or i == Num2):
            continue #If you don't want to consider the start and end so you can use continue 
        if (int(i%2==1)):
            count2+=i
    print(f"The sum of the odd numbers is: {count2}") # if your using above 3.5 python so u can use this type of formating also.

def sum_even(Num1, Num2):
    count1 = 0
    for i in range(Num1, Num2+1):
        if(i == Num1 or i == Num2):
            continue #If you don't want to consider the start and end so you can use continue 
        if(i % 2 == 0):
            count1 += i
    return count1

sum_of_odd = sum(filter(lambda x: (x % 2 != 0), range(Num1, Num2+1))) # Another way of doing
sum_of_even = sum(filter(lambda x: (x % 2 == 0), range(Num1, Num2+1))) #Another way of doing