Python Program Digits Product

By | May 15, 2022

In this tutorial we shall learn to write a Python program to print product that is multiplication of digits of a given number.

Program statement:

Write a program to display product of the digits of a number accepted from the user.

How this Python Program Product of digits Works?

Dear readers, when we divide a number by 10 and take remainder we will get the last digit of that number. For example, number is 123.

When we divide 123 by 10 and get remainder, the remainder will give you the last digit that is 3.

Python Program digits Product

Next time we will divide the quotient=12 of the last division by 10 again. this time the remainder is 2 and the quotient is 1.

Now we will divide the quotient=1 of the last division by 10 again.

This division will provide a remainder = 1.

Hence we find the three digits 3, 2 and 1. We will multiply remainders that is digits in the loop by the statement p = p* rem.

Product of digits of given number Python Programming

Code of the Python Program Multiplying digits of a number

#Write a program to display product of the 
#digits of a number accepted from the user.
num=int(input("Enter any number"))
p=1
n=num
while(n>0):
   rem=n%10
   prod=prod*rem
   n=n//10
print("Product of digits of  "+num+" is=",prod)

Output of the Python Program

Enter any number:123
Product of digits of 123 is= 6

Another main line of the above mentioned Python program is:

rem=n%10

This line will give remainder of the division.

prod=prod*rem     #this line multiplies digits

And the line :

n=n//10      # gives the integer quotient after performing integer division

The main loop while n>0 will run as long as n is not zero. In above example output the number entered is 123 so the while loop will run for 3 times.

First time 3 is multiplied by 1 and result is prod=3. Second time 2 is multiplied by by 3 and prod=6. Last time prod is multiplied by 1 and the prod=6, which is the required result of Python program to get product of the digits of a number.

 

 

 327 total views,  3 views today

Leave a Reply

Your email address will not be published.