How to Judge Armstrong Number in Python


In this example we will show how to check if a number is an Armstrong number in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Get the number entered by the user
num = int(input("Please enter a number: "))

# Define variable sum
sum = 0

# Get the length of number
n = len(str(num))
temp = num
while temp > 0:
    digit = temp % 10
    # Take the remainder and get the last digit of the current value
    sum += digit ** n
    temp //= 10

# Output result
if num == sum:
    print(num, "is Armstrong number")
else:
    print(num, "is not Armstrong number")

Output:

Please enter a number: 6
6 is Armstrong number

Please enter a number: 10
is not Armstrong number
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments