This article show you, How to write a Python Program to find Sum and Average of N Natural Numbers using While Loop, For Loop and Functions with example.

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

This Python program allows user to enter any integer value. Next, this program will calculate the sum and average of natural numbers from 1 to user specified value using For Loop.

# 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))

**OUTPUT**

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

In this program, we replaced the For Loop with While Loop

# 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))

**OUTPUT**

## Python Program to calculate Sum and Average of N Natural Numbers using Functions

In this program, we created a new function to find sum and average of natural numbers. Inside this function, we used If Else statement

# 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))

**OUTPUT**

## Python Program for Sum and Average of N Natural Numbers using Functions

This program is same as above example, but this time we are using Recursion.

# 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))

**OUTPUT**