While Loop
1. printing numbers from 1 to 10.
i=1
while i<=10:
print(i, end=' ')
i+=1
2. examples of while loops in Python for Printing those numbers divisible by either 5 or 7 within 1 to
50 using a while loop.
i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1
3. while loops in Python, the sum of squares of the first 15 natural numbers using a while loop.
num = 15
# initializing summation and a counter for iteration
summation = 0
c=1
while c <= num: # specifying the condition of the loop
summation = c**2 + summation
c = c + 1 # incrementing the counter
print("The sum of squares is", summation)
4. use the while loop for printing the multiplication table of a given number.
num = 21
counter = 1
# we will use a while loop for iterating 10 times for the multiplication table
print("The Multiplication Table of: ", num)
while counter <= 10: # specifying the condition
ans = num * counter
print (num, 'x', counter, '=', ans)
counter += 1 # expression to increment the counter
For Loop
5.Write a program to input a number and display sum of all the digits of number.
a=input("Enter Number : ")
res=0
for i in range(0,len(a)):
res=(res+int(a[i]))
print("Sum of digit Number is : ",res)
6. Write a program to input a number and display whether number is Prime or
not
a=int(input("Enter a Number : ")) flg=0
for i in range(1,a):
for j in range(2,i):
if(i%j==0):
flg=0
break
else:
flg=1
if(flg==1):
print("Not Prime")
else:
print("Prime")
7. Write a program to input a number and print whether number is Palindrom or not
n=int(input("Enter number:")) temp=n
rev=0
while(n>0):
d=n%10
rev=rev*10+d
n=n//10
if(temp==rev):
print("number is a palindrome!") else:
print("number isn't a palindrome!")
8. Write a program to input a string and print whether string is Palindrom or
not
x = input("Enter String : ")
w = ""
for i in x:
w=i+w
if (x==w):
print("String is Palindrome")
if(x!=w):
print("String is not Palindrome")