编写一个 Python 程序,使用 For 循环和示例查找从 1 到 N 的奇偶数之和。
Python 程序用于查找从 1 到 N 的奇偶数之和(使用 For 循环)
此 Python 程序允许用户输入最大限制值。接下来,它将打印从 1 到用户输入的限制值之间的偶数和奇数。在此示例中,For 循环确保数字在 1 和最大限制值之间。接下来,我们使用 If Else 来检查偶数。
提示:我建议您参考 偶数之和 和 奇数之和 文章,以了解奇偶数之和背后的 For 循环逻辑。同时参考 奇偶数程序 和 If Else 来理解 Python 逻辑。
# Python Program to find Sum of Even and Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
even_total = 0
odd_total = 0
for number in range(1, maximum + 1):
if(number % 2 == 0):
even_total = even_total + number
else:
odd_total = odd_total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, even_total))
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, odd_total))
Python 使用 For 循环计算奇偶数之和的输出

Python 程序用于计算不带 If 语句的从 1 到 N 的奇偶数之和
这个 Python 奇偶数之和程序与上面相同。但是,这个 Python 程序 允许用户输入最小值和最大值。接下来,它将打印最小值和最大值之间的偶数和奇数。
# Python Program to find Sum of Even and Odd Numbers from 1 to N
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
even_total = 0
odd_total = 0
for number in range(minimum, maximum + 1):
if(number % 2 == 0):
even_total = even_total + number
else:
odd_total = odd_total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, even_total))
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, odd_total))
Please Enter the Minimum Value : 10
Please Enter the Maximum Value : 40
The Sum of Even Numbers from 1 to 40 = 400
The Sum of Odd Numbers from 1 to 40 = 375