PYTHON WHILE LOOP
The while loop can execute a block of statements repeatedly till the condition is true.Python syntax for while loop
while condition:
Statement(s)
|
First the condition of while loop is checked; if it is true then the statements in the body of while loop are executed. After the execution, again the condition of while loop is checked and if it is found to be true then again the statements of while loop are executed. These statements are executed continuously till the condition is true and when the condition becomes false, the loop terminates and the control comes out of the loop.
Flow Chart of while loop
![]() |
Flow Chart of while loop |
Example 1: Print numbers from 1 to 10.
Coding:
#initialize num variable with 1
num=1
#check the value of num is less than equal to 10
while num<=10:
print (num)
#incrementing the value of num by 1
num += 1
|
Output:
1
2
3
4
5
6
7
8
9
10
|
Example 2: Calculate the sum of numbers from 1 to 10.
Coding:
#initialize n and sum with 10 and 0 respectively
num = 10
sum=0
#check the value of num is greater than equal to 0
while (num >= 0):
#incrementing the value of sum by the value of num
sum = sum + num
#decrement the value of
num by 1
num=
num – 1
#print the value of sum variable
print
("The sum is: ", sum)
|
Output:
The sum is: 55
|
Example 3: Find the sum of digits
Coding:
#initialize sum with 0
sum=0
#store user input into num variable
num=int(input("Enter the number:"))
#check the value of num is greater than equal to 0
while (num >= 0):
rem = num % 10
sum = sum +
rem
num = num //
10
#print the value of sum variable
print("The
sum of digits:", sum)
|
Output:
Enter the number:444
The sum of digits: 12
|
No comments:
Post a Comment
please do not enter any spam link in the comment box