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 SNIPPET
num = 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)
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 variable
numwith the statements/strings
("Enter a positive number"), we use the
intfunction 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 iteration
sum = 0, then a
whileloop with the condition
(num > 0)followed by a
:with the assignment operators
sum += numand
num -= 1.
- In the
ifstatement, if the condition is satisfied, the
("Enter a positive number"). If not, it moves to the next step which is the
- At the start, the
sumis initialized to
0. And, the number is stored in variable
num. Then, we used the
whileloop to iterate until
numbecomes zero. In each iteration of the loop, we have added the
sumand the value of
numis decreased by
- Once the
numvalue becomes zero the iteration comes to an end the
("\nThe sum is",sum).
- 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.