Python Tutorial: Loop Related Program in Python

Tuesday, 28 July 2020

Loop Related Program in Python

List of loop programming exercises
1)      Write a Python  program to print all natural numbers from 1 to n. - using while or for loop.
Answer :
#Using for loop
for i in range(1,11,1):
    print(i,end=" ")
#Using while loop
print()
i=1
while(i<11):
    print(i,end=" ")
    i=i+1
   
2)      Write a Python  program to print all natural numbers in reverse (from n to 1). - using while or for loop.
Answer:
#Using for loop
n=int(input("Enter the limit to print all natural numbers :"))
for i in range(n,0,-1):
    print(i,end=" ")
#Using while loop
print()
while(n>=1):
    print(n,end=" ")
    n=n-1
   
3)      Write a Python  program to print all alphabets from a to z. - using while or for loop.
Answer:
#Using for loop
for i in range(65,91,1):
    print(chr(i),"->",i)
#Using while loop
print()
i=65
while(i<=90):
    print(chr(i),"->",i)
    i=i+1
4)      Write a Python  program to print all even numbers between 1 to 100. - using while or for loop
Answer:
#Using for loop
for i in range(0,101,2):
    print(i,end=",")
#Using while loop
print()
i=2
while(i<=100):
    print(i,end=",")
    i=i+2
5)      Write a Python  program to print all odd number between 1 to 100.
Answer:
#Using for loop
for i in range(1,100,2):
    print(i,end=",")
#Using while loop
print()
i=1
while(i<=100):
    print(i,end=",")
    i=i+2
6)      Write a Python  program to find sum of all natural numbers between 1 to n.
Answer:
#Using for loop
n=int(input("Enter the limit : "))
s=0
for i in range(1,n+1,1):
    print(i,end=",")
    s=s+i
print("Sum=",s)
#Using while loop
print()
n=int(input("Enter the limit : "))
s=0
i=1
while(i<=n):
    print(i,end=",")
    s=s+i
    i=i+1
print("Sum=",s)
7)      Write a Python  program to find sum of all even numbers between 1 to n.
Answer :
#Using for loop
n=int(input("Enter the limit : "))
s=0
for i in range(2,n+1,2):
    print(i,end=",")
    s=s+i
print("Sum=",s)
#Using while loop
print()
n=int(input("Enter the limit : "))
s=0
i=2
while(i<=n):
    print(i,end=",")
    s=s+i
    i=i+2
print("Sum=",s)
8)      Write a Python  program to find sum of all odd numbers between 1 to n.
Answer :
#Using for loop
n=int(input("Enter the limit : "))
s=0
for i in range(1,n+1,2):
    print(i,end=",")
    s=s+i
print("Sum=",s)
#Using while loop
print()
n=int(input("Enter the limit : "))
s=0
i=1
while(i<=n):
    print(i,end=",")
    s=s+i
    i=i+2
print("Sum=",s)
9)      Write a Python  program to print multiplication table of any number.
Answer :
#Using for loop
n=int(input("Enter the limit : "))
t=1
for i in range(1,11,1):
    print(i,'x',n,'=',i*n)
#Using while loop
print()
n=int(input("Enter the limit : "))
i=1
while(i<=10):
    print(i,'x',n,'=',i*n)
    i=i+1
10)  Write a Python  program to count number of digits in a number.
            Input 
                
Enter a number : 3457
            Output
                Count of digits : 4
Answer :
n=int(input("Enter the number: "))
rem=count=sum1=0
while(n>0):
    rem=n%10
    n=n//10
    count=count+1
print("Count of digits :",count)
11)  Write a Python  program to find first and last digit of a number.
        Input 
                
Enter a number : 3457
        Output
                
First digit = 3
                Last digit = 7
Answer :
import math
n=int(input("Enter a number :"))
# Find last digit
lastDigit = n % 10    
# Total number of digits - 1
digits = (int)(math.log10(n))
# Find first digit
firstDigit = (int)(n // math.pow(10, digits))
print("First digit = ", firstDigit)
print("Last digit = ", lastDigit)
12)  Write a Python  program to find sum of first and last digit of a number.
         Input 
                
Enter a number : 3457
        Output
                
First digit = 3
                Last digit = 7
                Sum of First digit and Last digit :10
Answer
import math
n=int(input("Enter a number :"))
# Find last digit
lastDigit = n % 10    
# Total number of digits - 1
digits = (int)(math.log10(n))
# Find first digit
firstDigit = (int)(n // math.pow(10, digits))
print("First digit = ", firstDigit)
print("Last digit = ", lastDigit)
s=firstDigit+lastDigit
print("Sum of First digit and Last digit :",s)
13)  Write a Python  program to swap first and last digits of a number.
        Example :
                Input 
                        
Input any number : 12345
                Output
                        
Number after swapping first and last digit : 52341
       Answer :
import math
num=int(input("Enter any number: "))
# Find last digit
lastDigit= num%10
# Find total number of digit - 1
digits     = (int)(math.log10(num))
# Find first digit
firstDigit = (int)(num // math.pow(10, digits))
swappedNum  = lastDigit
swappedNum *= (int) (math.pow(10, digits))
swappedNum += num % ((int) (math.pow(10, digits)))
swappedNum -= lastDigit
swappedNum += firstDigit
print("Original number = ", num)
print("Number after swapping first and last digit: ", swappedNum)
14)  Write a Python  program to calculate sum of digits of a number.
        Example : 235=2+3+5=10   # sum of digits
Answer :
n=int(input("Enter any number :"))
s=r=0
while(n>0):
    r=n%10
    s=s+r
    n=n//10
print("The sum of digits :",s)
15)  Write a Python program to calculate product of digits of a number.
        Example : 
235=2*3*5=30   # sum of digits
Answer :
n=int(input("Enter any number :"))
r=0
s=1
while(n>0):
    r=n%10
    s=s*r
    n=n//10
print("The sum of digits :",s)
16)  Write a Python  program to enter a number and print its reverse.
    Example :
                Input 
                        
Input any number : 12345
                Output
                        The Reverse number is : 54321
Answer:
n=int(input("Enter any number :"))
s=r=0
while(n>0):
    r=n%10
    s=s*10+r
    n=n//10
print("The Reverse number is :",s)
17)  Write a Python  program to check whether a number is Armstrong  or not.
        Example : 
153=1*1*1+5*5*5+3*3*3      # 153 is an Armstrong number.
Answer:
n=int(input("Enter any number :"))
r=s=0
m=n
while(n>0):
    r=n%10
    s=s+r**3
    n=n//10
if(m==s):
    print(m, " is armstrong number.")
else:
    print(m, " is not armstrong number.")
18)  Write a Python  program to enter a number and print it in words.
        Input
                 Enter any number to print in words: 3462
        Output
            Three Four Six Two
Answer:
import math
n=int(input("Enter any number to print in words: "))
##Store reverse of n in num
num=0
#Find total digits in n
digits = (int) (math.log10(n))
while(n != 0):
    num = (num * 10) + (n % 10)
    n //= 10
#Find total trailing zeros
digits =  digits - (int) (math.log10(num))
#Extract last digit of number and print corresponding digit in words till num becomes 0
while(num!=0):
    rem=num % 10
    if (rem==0):
        print("Zero ",end='')
    if (rem==1):
        print("One ",end='')
    if (rem==2):
        print("Two ",end='')
    if (rem==3):
        print("Three ",end='')
    if (rem==4):
        print("Four ",end='')
    if (rem==5):
        print("Five ",end='')
    if (rem==6):
        print("Six ",end='')
    if (rem==7):
        print("Seven ",end='')
    if (rem==8):
        print("Eight ",end='')
    if (rem==9):
        print("Nine ",end='')
    num = num // 10
# all trailing zeros
while(digits):   
        print("Zero ")
        digits=digits-1
19)  Write a Python  program to print all ASCII character with their values.-using for or while loop.
       
Answer:
#Using for loop
for i in range(0,256,1):
    print(i,"->",chr(i))
#Using while loop
print()
i=0
while(i<=256):
    print(i,"->",chr(i))
    i=i+1
   
20)  Write a Python  program to find power of a number using for loop.
    Example
Input
    Input base: 2
    Input exponent: 5
Output
    2 ^ 5 = 32
Answer:
#Input base and exponent from user
base=int(input("Enter base: "))
exponent=int(input("Enter exponent: "))
power = 1
#Multiply base, exponent times
for i in range(1,exponent+1, 1):
    power = power * base
print(base,"^", exponent,"=", power)
21)  Write a Python  program to find all factors of a number
Example

    Input number: 12
Output
    Factors of 12: 1, 2, 3, 4, 6, 12
Answer:
num=int(input("Enter any number to print Prime factors: "))
print("All Prime Factors of ",num," are: ",end="")
# Find all Prime factors
for i in range(2, num+1, 1):
# Check 'i' for factor of num
    if(num%i==0):
# Check 'i' for Prime
        isPrime = 1
        for j in range(2, i+1//2,1):
            if(i%j==0):
                isPrime = 0
                break
# If 'i' is Prime number and factor of num
        if(isPrime==1):       
            print(i,end=",")
       
22)      Write a Python  program to calculate factorial of a number.
            Factorial -> 5= 5*4*3*2*1=120
            Example 
                Enter the number : 5
            Output
                The factorial of 5 is 120     
Answer :
num=int(input("Enter the number : "))
fact=1
if (num < 0):
   print("Sorry, fact does not exist for negative numbers")
elif (num == 0):
   print("The fact of 0 is 1")
else:
   for i in range(1,num + 1):
       fact = fact*i
   print("The factorial of",num,"is",fact)
23)  Write a Python  program to find HCF (GCD) of two numb
        Input
            Input first number: 12
            Input second number: 30
        Output
            HCF of 12 and 30: 6
Answer:
num1=int(input("Enter any first number : "))
num2=int(input("Enter any second number : "))
    # Find minimum between two numbers
if(num1<num2):
    mx=num1
else:
    mx=num2
for i in range(1, mx+1,1):
    # If i is factor of both number
    if(num1%i==0 and num2%i==0):
        hcf = i
print("HCF of ",num1, "and",num2,  "=" , hcf)
24)  Write a Python  program to find LCM of two numbers.
                Example
                    Input
                            Enter any first number : 12
                            Enter any second number : 30
                    Output
Answer:
num1=int(input("Enter any first number : "))
num2=int(input("Enter any second number : "))
# Find maximum between num1 and num2
if(num1<num2):
    mx=num1
else:
    mx=num2
# First multiple to be checked
i = mx
# Run loop indefinitely till LCM is found
while(True):
    if(i%num1==0 and i%num2==0):
    #If 'i' divides both 'num1' and 'num2' then 'i' is the LCM.
        lcm = i
    # Terminate the loop after LCM is found
        break
    #If LCM is not found then generate next multiple of max between both numbers   
    i += mx
print("LCM of ",num1, "and",num2 ," = ",lcm)
25)  Write a Python  program to check whether a number is Prime number or not.
            Example
Input any number: 17
17 is prime number
Answer:
num=int(input("Enter any number to check prime: "))
isPrime = 1
for i in range(2,num//2+1,1):
  # Check divisibility of num
    if(num%i==0): 
        # Set isPrime to 0 indicating it as composite number
        isPrime = 0
        # Terminate from loop
        break
#If isPrime contains 1 then it is prime
if(isPrime == 1 and num > 1):
    print(num," is prime number", )
else:
    print(num," is composite number" )
26)  Write a Python  program to print all Prime numbers between 1 to n.
Input
    Find prime numbers between 1 to : 20
Output
    All prime numbers between 1 to 20 are: 2, 3, 5, 7, 13, 17, 19
Answer:
end=int(input("Find prime numbers between 1 to : "))
print("All prime numbers between 1 to ",end," are: ")
# Find all Prime numbers between 1 to end
for i in range(2, end+1,1):
# Assume that the current number is Prime
    isPrime = 1
# Check if the current number i is prime or not
    for j in range(2, i//2+1,1):
#  If i is divisible by any number other than 1 and self then it is not prime number
        if(i%j==0):       
            isPrime = 0
            break
# If the number is prime then print
    if(isPrime==1):
        print(i,end="\t")
   
27)  Write a Python  program to find sum of all prime numbers between 1 to n.
Answer:
end=int(input("Find prime numbers between 1 to : "))
print("All prime numbers between 1 to ",end," are: ")
# Find all Prime numbers between 1 to end
s=0
for i in range(2, end+1,1):
# Assume that the current number is Prime
    isPrime = 1
# Check if the current number i is prime or not
    for j in range(2, i//2+1,1):
#  If i is divisible by any number other than 1 and self then it is not prime number
        if(i%j==0):       
            isPrime = 0
            break
# If the number is prime then print
    if(isPrime==1):
        s=s+i
        print(i,end="\t")
print("\nSum of all prime numbers between 1 to ",end," = ",s)
Program to find sum of prime numbers in given range
Answer:
start=int(input("Enter lower limit: "))
end=int(input("Enter upper limit: "))
sum1=0
#Find all prime numbers in given range */
for i in range(start, end+1,1):
#Check if the current number i is Prime or not */
    isPrime = 1
    for j in range(2, i//2+1,1):   
        if(i%j==0):       
            # 'i' is not prime */
            isPrime = 0
            break
# If i is Prime then add to sum1
    if(isPrime==1):   
        sum1 += i 
print("sum1 of all prime numbers between ", start," to ", end," = ", sum1)

28)  Write a Python  program to check whether a number is Armstrong number or not.
Answer:
What is Armstrong number?
An Armstrong number is a n-digit number that is equal to the sum of the nth  power of its digits. For example -
153 = 13 + 53 + 33 = 153
Source Code
num=int(input("Enter any number to check Armstrong number: "))
sum1 = 0
# Copy the value of num for processing
Num1 = num
# Calculate sum of power of digits
while(num > 0):
    # Extract the last digit
    rem = num % 10
    # Compute sum of power of last digit
    sum1 = sum1 +rem**3
    # Remove the last digit
    num = num // 10
# Check for Armstrong number
if(Num1 == sum1):
    print(Num1," is ARMSTRONG NUMBER.")
else:
    print(Num1," is NOT ARMSTRONG NUMBER.")
29)  Write a Python  program to print all Armstrong numbers between 1 to n.
Answer:
limit=int(input("Enter upper limit: "))
print("Armstrong number between 1 to ",limit, " are: ", end="")
for i in range(1, limit+1,1):
    sum1 = 0
# Copy the value of num for processing
    num = i
# Calculate sum of power of digits
    while(num > 0):
# Extract last digit
        rem = num % 10
        sum1 = sum1 + rem**3
# Remove the last digit
        num = num // 10
# Check for Armstrong number
    if(i == sum1):
        print(i,end=",")
    
30)  Write a Python program to check whether a number is Perfect number or not.
What is Perfect number?
Perfect number is a positive integer which is equal to the sum of its proper positive divisors.
For example: 6 is the first perfect number
Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6.
Hence 6 is a perfect number.
Answer:
num=int(input("Enter any number to check perfect number: "))
# Calculate sum of all proper divisors
sum1=0
for i in range(1, num//2+1,1):
# If i is a divisor of num
    if(num%i == 0):   
        sum1 += i   
# Check whether the sum of proper divisors is equal to num
if(sum1 == num):
    print(num," is PERFECT NUMBER")
else:
    print(num, " is NOT PERFECT NUMBER")
31)  Write a Python program to print all Perfect numbers between 1 to n.
Answer:
limit=int(input("Enter limit number: "))
# Calculate sum of all proper divisors
sum1=j=0
for i in range(1, limit+1,1):
    sum1=0
    for j in range(1, i//2+1,1):
    # If i is a divisor of num
        if(i%j == 0):   
            sum1 += j   
    # Check whether the sum of proper divisors is equal to num
    if(sum1 == i):
        print(i,end=",")
…………………other source code………………………………………….
start=int(input("Enter Start  number: "))
limit=int(input("Enter limit number: "))
# Calculate sum of all proper divisors
sum1=j=0
for i in range(start, limit+1,1):
    sum1=0
    for j in range(1, i//2+1,1):
    # If i is a divisor of num
        if(i%j == 0):   
            sum1 += j   
    # Check whether the sum of proper divisors is equal to num
    if(sum1 == i):
        print(i,end=",")
       
32)  Write a Python program to check whether a number is Strong number or not.
What is Strong number? Strong number is a special number whose sum of factorial of digits is equal to the original number.
A strong number is one in which the factorial of the digits equals the number itself. 1, 2, 145, and 40585 are some examples of strong numbers.
For example: 145 is strong number. Since, 1! + 4! + 5! = 145
Answer:
temp=n
s=0
while n!=0:
    r=n%10
    f=1 
    for i in range(1,r+1):
        f=f*i
    s=s+f
    n=n//10
if temp==s:
    print("Strong")
else:
    print("Not Strong")
33)  Write a Python program to print all Strong numbers between 1 to n.
Answer:
limit=int(input("Enter limit: "))
print("All Strong numbers between 1 to",limit, " are: ",  end=" ")
# Copy the value of num to a temporary variable
for i in range(1,limit+1,1):  
    sum1 = 0
    currentValue=i
    # Find sum of factorial of digits
    while(currentValue > 0):
        # Get last digit of num
        lastDigit = currentValue % 10
        # Find factorial of last digit
        fact = 1
        for j in range(1, lastDigit+1,1):
                fact = fact * j
        # Add factorial to sum
        sum1 = sum1 + fact
        currentValue = currentValue // 10
    # Check Strong number condition
    if(sum1 == i):
        print(i,end=",")
   
34)   Write a Python program to print Fibonacci series up to n terms.
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Answer:
limit=int(input("Enter the limit to print febonacci series.."))
a,b=0,1
c=0
for i in range(limit):
    c=a+b
    print(c,end=",")
    a,b=b,c
               
35)  Write a Python program to find one's complement of a binary number.
Ones complement of a binary number is defined as value obtained by inverting all binary bits. It is the result of swapping all 1s to 0s and all 0s to 1s.
Example
    Input binary number: 01000011
Output
    Ones complement: 10111100
Answer:
# one's compement
binary=input("Enter number in bit binary value :")
f=0
size=len(binary)
oneComp=""
for i in range(size):
    if(binary[i]=='1'):
        oneComp+='0'
    elif(binary[i]=='0'):
        oneComp+='1'
    else:
        print("Invalid input")
        f=1
        break
if(f==0):
    print("Original binary :",binary)
    print("Ones Compelement :", oneComp)
               
36)   Write a Python program to find two's complement of a binary number.
Twos complement of an N-bit number is defined as the complement with respect to 2n. It is the result of subtracting the number from 2N, which in binary is one followed by zeroes.
In simple words twos complement is defined as sum of ones complement of a binary number and 1.
Input
    Input binary number: 01101110
Output
    Twos complement: 10010010
Answer:
# twos compement
binary=input("Enter number in bit binary value :")
f=0
SIZE=len(binary)
onesComp=twosComp=""
carry=1
# Find ones complement of the binary number
for i in range(SIZE):
    if(binary[i] == '1'):   
        onesComp+='0'   
    elif(binary[i] == '0'):   
        onesComp+='1'
#Add 1 to the ones complement
for i in range(SIZE-1, -1,-1):
    if(onesComp[i]=='1' and carry == 1):   
        twosComp+='0'   
    elif(onesComp[i] =='0' and carry==1):   
        twosComp+='1'
        carry = 0   
    else:   
        twosComp+= onesComp[i]
print("Original binary = ", binary)
print("Ones complement = ", onesComp)
print("Twos complement = ", twosComp)
37)  Write a Python program to convert Binary to Octal number system.
Answer:
octalConstant = [0, 1, 10, 11, 100, 101, 110, 111]
# Input binary number from user
binary=int(input("Enter any binary number: "))
octal = 0
place= 1
# Copy original binary value to temp variable
tempBinary = binary
while(tempBinary != 0):
    # Extract last three digit of binary
    digit = tempBinary % 1000
    # Find octal equivalent of 3 digit binary
    for i in range(0,8,1):   
        if(octalConstant[i] == digit):
            octal = (i * place) + octal
            break
    # Remove the last three digit of binary
    tempBinary //= 1000
    # Increase the place value
    place *= 10
print("Original binary number = ", binary)
print("Octal number = ", octal)
38)  Write a Python program to convert Binary to Decimal number system.
Answer:
import math
binary=int(input("Enter any binary number: "))
N=decimal=0
BASE=2
tempBinary = binary
while(tempBinary!=0):
    # If current binary digit is 1
    if(tempBinary % 10 == 1):   
        decimal+=math.pow(BASE,N)
    N+=1
    tempBinary //= 10
print("Binary number = ", binary)
print("Decimal number= ",round(decimal))
39) Write a program to input a number and check whether it is 'Magic Number' or not. Display the message accordingly.
A number is said to be a magic number if the eventual sum of digits of the number is one.
Sample Input : 55
Then, 5 + 5 = 10, 1 + 0 = 1
Sample Output: Hence, 55 is a Magic Number.
Similarly, 289 is a Magic Number.
Ans:
n=int(input("Enter no. "))
while n>9:
    s=0
    while n!=0:
        s=s+n%10
        n=n//10
    n=s
if n==1:
    print("Magic Number")
else:
    print("Not Magic Number")

 

2 comments: