Check a number is Spy number or not in Python
In this article, you will learn how to check whether a number is a Spy number or not in Python programming.
Before we go forward, let me explain what is spy number in brief with examples:
A number is called as Spy number if the sum of its digits is equal to the product of its digits. exp. 1124,123,1412,132 …..
sum of digits: 1+1+2+4=8
product of digits: 1*1*2*4=8
Here, sum of digits is equal to the product of digits. So, this is a Spy number.
Python program for Spy number
To check the number is Spy number or not in Python program, we will use modulo operator (%), floor division operator (//), equality operator (==), explicit type conversion, if-else statement and while loop.
So, let’s get started:
num=int(input("enter a number ")) s=0 prod=1 while(num>0): b=num%10 s=s+b prod=prod*b num=num//10 if(s==prod): print('It is a Spy number') else: print('It is not a Spy number')
First of all, we will get input from the user. We know that input() function takes input as string data type.
num=int(input("enter a number "))
Here, we will use explicit type conversion and convert a string into an integer using int() function and store it in variable num.
Then takes a variable s as 0 and variable prod as 1.
The loop iterates while num>o evaluates to True.
Modulo operator is used to get remainder. As often as num will divide by 10 it will give last digit as remainder that will store in variable b.
The stored value in b will add with s and store in s and value of b will multiply with prod and store in prod.
Floor division will reduce last digit one by one of quotient and update the value of num.
When the value of num = 0, the while loop will terminate.
It is used to check whether the s is equal to prod or not. If it is True then if statement will run otherwise else statement will run.
enter a number 1124 It is a Spy number
enter a number 180 It is not a Spy number
I hope this article is useful for you. And if you have any doubts, then let me know in the comment section.