Python programs on digits: Sum of the digit, Reverse the digit, Count the digit

     This segment deals with programming on numbers and its digits .For example, To  reverse a number, just extract each number and add up with tens until it reaches to zero.

Three different programs are given below.

  • ·       Reverse the digit
  • ·       Sum of the digit
  • ·       Count the digit

 Python program to reverse the digit:

              It deals with extracting a digit from whole number and convert into tens and adds reminder.

#As a initial stage, get the input from the user.

no =  int(input("Enter(( the number"))

#assign value of zero to b

b = 0

#put a while loop, check the condition that no  > 0. Get the one’s place digit is by using % operator and store it into ‘a’. store the extracted value to b. divide the no by 10.

while no > 0 :

    a = no % 10

    b = (b * 10 ) + a

    no = no // 10

print ("The reverse of the number is:" ,b)

Finally ,print the output with the message.

Python program : count the digit:

This program finds the number of the digit from the number given,

#First, get the number from user.

no =  int(input("Enter the number"))

# Initialize c to 0

c = 0

# check the no is greater than zero or not. extract the last digit and store to a. Increase the count by one. Divide the no by 10. Repeat the loop.

while no > 0 :

    a = no % 10

    c = c + 1

    no = no // 10

print ("The number of digits in the number is:" ,c)

Output prints the counting of the digits.

Pyton programs : sum of the digits

This program adds the individual digits in a number.

#Get the input from the user and store it into no.

no =  int(input("Enter the number"))

#Assign a variable to assign 0 value to s.

s = 0

#In the while loop, check no > 0. If yes ,the control flows inside loop. It extracts one’s place digit and store it  a. add the a to sum value. Divide the no by 10. Repeat until, no > 0.

while no > 0 :

    a = no % 10

    s = s + a

    no = no // 10

print ("The sum of digits are " ,s)

The output is:


These are the some simple python programs on numbers and digits.

No comments:

Post a Comment