Sum of n Natural Numbers in Python Using While Loop

Sum of n natural numbers in python. In Python programming language, the sum of natural numbers. The natural numbers will be printed by this Python application. This software is essentially an extension program, but it adds in advanced features

num = 18
if num < 0:
print("Sum of the natural number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

 

Output

The sum is 171

If Else Statement in Python

You can create a chain of if statements using the if/else if statement. The if statements are evaluated one after the other until one of the if expressions is true or the if/else if chain ends. If there is no true expression at the end of the if/else if chain, no code blocks are executed. The if else structure is a decision-making structure in which the if statement is followed by an optional else statement that runs when the expression is false.

While Loop Statement in Python

Python while loop is a programming construct that is used to repeatedly execute a set of statements until a condition is met. When the condition in the program becomes false, the line immediately after the loop is performed. While loop is classified as an indefinite iteration.