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
我必须能够要求用户提供两个数字,然后我的程序应该能够将两个数字之间的所有偶数相加。我刚开始编程,所以没学到多少东西。我试着四处寻找答案,但这里的答案对我来说毫无意义,因为他们使用的技术对我来说太先进了。谢谢!
一旦你有了这两个数字,你就需要找到它们之间的所有偶数,对吧?
为了找到它们之间的所有数字,你可以使用
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的快速示例:
这使用了名为list comprehension的东西和内置方法sum。
现在,为了解释这一切是如何协同工作的:
Range,正如您已经知道的,返回两个参数之间的数字列表。
模运算符(%)用来除两个数,然后给你余数。这使得查找偶数变得非常方便:任何偶数除以2都将有0的余数。
列表理解使用这个技巧来构建一个包含给定范围内每个偶数的值的列表。
最后,
sum()
迭代并将该列表为您生成的所有值相加。这应该可以做到:
使用列表理解可以使其更加简洁:
不是这两个range函数,我使用了
end+1
,因为range只会上升到函数的第二个参数之前的数字。相关问题 更多 >
编程相关推荐