In this python tutorial, you will learn how to Calculate the Sum of Natural Numbers using the if and else statements along with the assignment operators of the python programming language.
How to Calculate the Sum of Natural Numbers?
Let’s take a look at the source code , here the values are given as input by the user in the code, the if and else statements and its conditions along with the while loop carry out the function.
RUN CODE SNIPPETnum = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("\nThe sum is",sum)INPUT:
16
OUTPUT:
Enter a number: The sum is 136
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction and are stored in the variablenumwith the statements/strings("Enter a positive number"), we use theintfunction and declare the input value as an integer value. - In the STDIN section of the code editor the input values are entered.
- We declare the
ifstatement with the start iterationsum = 0, then awhileloop with the condition(num > 0)followed by a:with the assignment operatorssum += numandnum -= 1. - In the
ifstatement, if the condition is satisfied, theprintfunction will display the statement("Enter a positive number"). If not, it moves to the next step which is theelsestatement. - At the start, the
sumis initialized to0. And, the number is stored in variablenum. Then, we used thewhileloop to iterate untilnumbecomes zero. In each iteration of the loop, we have added thenumtosumand the value ofnumis decreased by1. - Once the
numvalue becomes zero the iteration comes to an end theprintfunction will display the statement("\nThe sum is",sum).
NOTE:
- The input() function allows a user to insert a value into a program, it returns a string value.
- The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
- The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
- The While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line of code immediately after the loop in the program is executed.
- The Python += operator lets you add two values together and assign the resultant value to a variable, the -= operator function is similar which lets you subtract two values together and assign the resultant value to a variable.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.