Learn about Python Program to Find Sum of N Natural Numbers in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Sum of natural numbers N, denoted as sum = 1+2+3+4+5+….+(N-1)+N. To write the program, we can use a while or for loop. We can also create a Python program without the use of a loop.
Contents
Python Program to Find Sum of N Natural Numbers
To find the sum of natural numbers, this Python program uses a while loop. While declaring the variables, we shall use a natural number. Python program that uses a while loop to calculate the sum of n natural numbers and displays the result on the screen.
Program:
# Python program to find sum of n natural numbers
# input number
num = int(input('Enter a number: '))
# find sum of natural number
sum = 0
x = 1
while x <= num:
sum += x
x += 1
# print result
print('The sum of natural number =', sum)
Output:
Enter a number: 5
The sum of natural number = 15
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Largest among Three Numbers using max() Function in Python