写一个 Python示例,用 While 循环和 For 循环计算从 1 到 N 的偶数和,并举例说明。
这个 Python示例允许用户输入最大限制值。接下来,Python 将计算从 1 到用户输入值的偶数总和。
在这个例子中,我们使用 Python For Loop 将数字保持在 1 和最大值之间。
提示:建议大家参考 Python 偶数从 1 到 N 的文章,了解 Python 中打印偶数背后的逻辑。
# Python Program to Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(1, maximum+1):
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, total))
Python 偶数和输出
Please Enter the Maximum Value : 15
2
4
6
8
10
12
14
The Sum of Even Numbers from 1 to 15 = 56
这个 Python 偶数和程序和上面一样。但是我们修改了 Python For 循环来移除 If 块。
# Python Program to Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(2, maximum + 1, 2):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, total))
Python 偶数和使用 for 循环输出
Please Enter the Maximum Value : 12
2
4
6
8
10
12
The Sum of Even Numbers from 1 to 12 = 42
在这个 Python 偶数和的例子中,我们将循环的替换为而循环的。
# Python Program to Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
number = 1
while number <= maximum:
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
number = number + 1
print("The Sum of Even Numbers from 1 to N = {0}".format(total))
Python 使用 while 循环输出对偶数求和
Please Enter the Maximum Value : 20
2
4
6
8
10
12
14
16
18
20
The Sum of Even Numbers from 1 to N = 110
这个 Python示例允许用户输入最小值和最大值。接下来,Python 计算从最小值到最大值的偶数总和。
# Python Program to Calculate Sum of Even Numbers from 1 to 100
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(minimum, maximum+1):
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from {0} to {1} = {2}".format(minimum, number, total))
标签: 博客程序