您的位置:

Python 程序:求N个自然数的和与均值

写一个 Python 程序,用 While 循环、For 循环和函数的例子来求N个自然数的和与均值。

用 For 循环求N个自然数的和与均值的 Python 程序

该程序允许用户输入任意整数值。接下来,这个 Python 程序使用 For 循环计算从 1 到用户指定值的自然数的总和和平均值。

# Python Program to find Sum and Average of N Natural Numbers

number = int(input("Please Enter any Number: "))
total = 0

for value in range(1, number + 1):
    total = total + value

average = total / number

print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))
print("Average of Natural Numbers from 1 to {0} =  {1}".format(number, average))

用于循环输出的自然数的 Python 和与均值

Please Enter any Number: 5
The Sum of Natural Numbers from 1 to 5 =  15
Average of Natural Numbers from 1 to 5 =  3.0

使用 While 循环计算N个自然数的和与均值的 Python 程序

在这个寻找自然数的和与均值的 Python 程序中,我们将循环的替换为循环的。请参考 C 示例以迭代方式理解这个 Python 代码执行。

# Python Program to find Sum and Average of N Natural Numbers

number = int(input("Please Enter any Number: "))

total = 0
value = 1

while (value <= number):
    total = total + value
    value = value + 1

average = total / number

print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))
print("Average of Natural Numbers from 1 to {0} =  {1}".format(number, average))

Python 使用 while Loop 输出自然数的总和和平均值

Please Enter any Number: 10
The Sum of Natural Numbers from 1 to 10 =  55
Average of Natural Numbers from 1 to 10 =  5.5

用函数计算N个自然数的和与均值的 Python 程序

在这个寻找自然数的和与均值的 Python 程序中,我们创建了一个新的函数来寻找自然数的和与均值。在这个函数中,我们使用了 If Else 语句

# Python Program to find Sum and Average of N Natural Numbers

def sum_and_avg_of_natural_numbers(num):
    if(num == 0):
        return num
    else:
        return (num * (num + 1) / 2)

number = int(input("Please Enter any Number: "))

total = sum_and_avg_of_natural_numbers(number)
average = total / number

print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))
print("Average of Natural Numbers from 1 to {0} =  {1}".format(number, average))

Python 使用函数输出自然数的总和和平均值

Please Enter any Number: 100
The Sum of Natural Numbers from 1 to 100 =  5050.0
Average of Natural Numbers from 1 to 100 =  50.5

用递归实现N个自然数的和与均值的 Python 程序

这个 Python 程序求自然数的和与均值和上面的例子一样,但是这次我们用的是递归。

# Python Program to find Sum and Average of N Natural Numbers

def sum_and_avg_of_natural_numbers(num):
    if(num == 0):
        return num
    else:
        return (num + sum_and_avg_of_natural_numbers(num - 1))

number = int(input("Please Enter any Number: "))

total = sum_and_avg_of_natural_numbers(number)
average = total / number

print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))
print("Average of Natural Numbers from 1 to {0} =  {1}".format(number, average))