写一个 Python示例,用 While 循环、For 循环和带有例子的函数来求N
个自然数的和。
N
个自然数之和的 Python示例这个 Python示例允许用户输入任何整数值。接下来,它使用 For 循环计算从 1 到用户指定值的自然数总和。
number = int(input("Please Enter any Number: "))
total = 0
for value in range(1, number + 1):
total = total + value
print("The Sum of Natural Numbers from 1 to {0} = {1}".format(number, total))
Please Enter any Number: 25
The Sum of Natural Numbers from 1 to 25 = 325
N
个自然数之和的 Python示例在这个 Python 自然数求和程序中,我们刚刚用代替了 For Loop ,而 Loop
num = int(input("Please Enter any Num: "))
total = 0
value = 1
while (value <= num):
total = total + value
value = value + 1
print("The Sum from 1 to {0} = {1}".format(num, total))
Please Enter any Num: 12
The Sum from 1 to 12 = 78
N
个自然数之和的 Python示例在这个 Python示例中,我们创建了一个新的函数来求自然数的和。在这个函数中,我们使用了 If Else 语句。
def sum_of_n_natural_numbers(num):
if(num == 0):
return num
else:
return (num * (num + 1) / 2)
number = int(input("Please Enter any Number: "))
total_value = sum_of_n_natural_numbers(number)
print("Sum from 1 to {0} = {1}".format(number, total_value))
Please Enter any Number: 100
Sum from 1 to 100 = 5050.0
N
个自然数之和的 Python示例这个 Python 自然数求和程序与上面的例子相同,但是这次我们使用的是递归。
def sum_of_n_natural_numbers(num):
if(num == 0):
return num
else:
return (num + sum_of_n_natural_numbers(num - 1))
number = int(input("Please Enter any Number: "))
total_value = sum_of_n_natural_numbers(number)
print("Sum of Natural Numbers from 1 to {0} = {1}".format(number, total_value))
标签: 手机支付