我需要用Python把另外两个数字之间的偶数相加

2024-09-25 06:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

print "This program computes and prints the sum of all even values"
print "between 2 and a positive integer value entered by the user. \n"

integer = input("Enter a positive integer: ")
while integer <2:
        if integer <2:
            print "Integer must be greater than 2!"
        integer = input("Enter a positive integer: ")
else:
    integer2 = input("Now enter a second integer: ")

evens = (integer - integer2)/2 + 1

while True

我必须能够要求用户提供两个数字,然后我的程序应该能够将两个数字之间的所有偶数相加。我刚开始编程,所以没学到多少东西。我试着四处寻找答案,但这里的答案对我来说毫无意义,因为他们使用的技术对我来说太先进了。谢谢!


Tags: andthe答案input数字integerthisprogram
3条回答

一旦你有了这两个数字,你就需要找到它们之间的所有偶数,对吧?

为了找到它们之间的所有数字,你可以使用range(integer,integer2+1)(这里有+1,因为我假设你想要它包括integer2)。 若要查找该范围内的所有偶数,请使用filter(lambda x: x%2==0, range(integer, integer2+1)),然后对所有使用sum()的偶数求和。。所以最后:

sum(filter(lambda x: x%2==0, range(integer, integer2+1)))

下面是一个使用交互式shell的快速示例:

>>> x = 9
>>> y = 31
>>> sum([z for z in range(x, y + 1) if z % 2 == 0])
220

这使用了名为list comprehension的东西和内置方法sum

现在,为了解释这一切是如何协同工作的:

Range,正如您已经知道的,返回两个参数之间的数字列表。

>>> range(x, y + 1)
[9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

模运算符(%)用来除两个数,然后给你余数。这使得查找偶数变得非常方便:任何偶数除以2都将有0的余数。

>>> 5 % 2
1
>>> 4 % 2
0

列表理解使用这个技巧来构建一个包含给定范围内每个偶数的值的列表。

>>> [z for z in range(x, y + 1) if z % 2 == 0]
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]

最后,sum()迭代并将该列表为您生成的所有值相加。

>>> sum([z for z in range(x, y + 1) if z % 2 == 0])
220

这应该可以做到:

start = 0
end = 0

while start < 2 or end <= start:
    start = int(raw_input("Enter start -> "))
    end = int(raw_input("Enter end ->"))

total = 0
for x in range(start, end+1):
    if x % 2 == 0:
        total += x

print total

使用列表理解可以使其更加简洁:

start = 0
end = 0

while start < 2 or end <= start:
    start = int(raw_input("Enter start -> "))
    end = int(raw_input("Enter end -> "))

print sum([x for x in range(start, end+1) if x % 2 == 0])

不是这两个range函数,我使用了end+1,因为range只会上升到函数的第二个参数之前的数字。

相关问题 更多 >