In this Python example you are going to learn how to find a number is an Armstrong number or not. An “Armstrong number” is a number that is equal to the sum of the nth powers of its individual digits. For example, 371 is an Armstrong number where it has 3 digits and 337313 = 371
Here is the Python script for finding the Armstrong number.
print("Enter the number")
#get the number
number = int(input())
#store it in a temp
temp = int(number)
Sum = 0
#loop till the quotient is 0
while(temp != 0):
rem = temp % 10 #find reminder
Sum = Sum + (rem * rem * rem) #cube reminder and add it to the Sum
temp = temp / 10 #find quotient, if 0 then loop again
#if the entered number and the Sum value matches, it is an Armstrong number
if(number == Sum):
print ("Armstrong Number")
else:
print ("Not an Armstrong Number")
The above code is self explanatory, just read the comments to understand it.
Below are the Armstrong number, use these number to test this above code:
1. 153
2. 371
3. 407
And if you are looking for web based Python CGI Script to test Armstrong number, here it is:
#!/usr/bin/python
print "Content-type: text/html\n\n";
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
number = form.getvalue('number')
if(number):
#store it in a temp
temp = int(number)
Sum = 0
#loop till the quotient is 0
while(temp != 0):
rem = temp % 10 #find reminder
Sum = Sum + (rem * rem * rem) #cube reminder and add it to the Sum
temp = temp / 10 #find quotient, if 0 then loop again
#if the entered number and the Sum value matches, it is an Armstrong number
if(int(number) == Sum):
print "Armstrong Number"
else:
print "Not an Armstrong Number"
print '''
<html>
<body>
<h3>Web Based Python script to Find Armstrong Number - <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h3>
<form action="" method="post">
<label>Enter a number to check <label>
<input type="text" name="number" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
'''
And finally the Demo,
