The while loop:
A while loop is a conditional loop that will repeat the instructions within itself as
long as a condition remains true.
Syntax
while <logical expression>:
Block of Statement
else:
Body of else
Example1: Program to calculate the factorial of a number:
num=int(input("enter the number"))
fact=1
a=1
while a<=num:
fact=fact*a
a+=1
print("the factorial of", num, "is", fact)
Example2: Program to calculate and print the sums of even and odd integers of
the first n natural number:
n=int(input("Up to which natural number?"))
c=1
sum_even=sum_odd=0
while c<=n:
if c%2==0:
sum_even=sum_even+c
else:
sum_odd=sum_odd+c
c+=1
print(“the sum of even integers is”, sum_even)
print(“the sum of odd integers is”, sum_odd)
Practice Programs:
Q.1 WAP to print the even numbers between 1 and 30;
Q.2 WAP to print the odd numbers between 1 and 30;
Q.3 WAP to print the following series 1, 4, 7, 10, 13, 16, 19.
Q.4 WAP to print the following series 1, 8, 27, 64, 125.
Q.5 WAP to find and print the sum of 1 to 10 natural numbers.
Q.6 WAP to find and print the sum of odd numbers between 1 to 20 .
Q.7 WAP to find and print the sum of even numbers between 1 to 20 .
Q.8 WAP to find and print the sum of numbers that are divisible by 3 between 1 to 20 .
Q.9 WAP to find and print the average of 1 to 10 natural numbers.
Q.10 WAP to find and print the average of all even numbers between 1 to 20.
Q.11 WAP to print Fibonacci series: 0,1,1,2,3,5,8,13,21.
Q.12 WAP to enter a number and check if it a prime number or not.
Q. 13 WAP to accept a number and check whether it is an Armstrong number or not.
(Example: 371 is an Armstrong Number: 3**3 + 7**3 +1**3=371)
Q.14 WAP to accept a number and display whether he number is a Palindrome or not.
Q.15 WAP that accept a number from the user and print the sum of its digits.