Python Program to Check Armstrong Number

Python Program to Check Armstrong Number

July 6th, 2026
10
10: 00 Minutes

Finding Armstrong numbers using Python code is one of the popular exercises for Python interviews. It is asked to test your skills on number theory problems. Do you know what armstrong numbers are and how to find them using Python programs?

No problem, we will learn everything in this guide. It includes the definition and basic examples of Armstrong numbers, along with multiple Python programs that demonstrate various approaches to checking Armstrong numbers.

What is an Armstrong Number?

An Armstrong number is a special kind of number that is equal to the sum of its own digits, each raised to the power of the number of digits in that number. These are also known as narcissistic numbers or pluperfect digital invariant. Here is a mathematical representation of these numbers

Armstrong Number = d₁ⁿ + d₂ⁿ + d₃ⁿ + ... + dₙⁿ

Here n is the total number of digits and d₁, d₂, ... are the individual digits.

A Simple Definition: Take every digit of a number, raise each to the power equal to the digit count, add them all up, if the result equals the original number, it's an Armstrong number.

Read Also: Python Exception Handling

Armstrong Number Examples

Here are some of the common examples of Armstrong Numbers to help you how understand them perfectly:

Number Calculation
153 (3-digit number) 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
370 (3-digit number) 3³ + 7³ + 0³ = 27 + 343 + 0 = 370
9474 (4-digit number) 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474

Python Program to Check Armstrong Number

We have different methods to check Armstrong numbers using Python programs, based on the concept. We will walk through each of them, so you will be ready to counter each question asked in interviews. Let’s begin the most basic approach!

Method 1: Using a While Loop

This is the most basic method and great for beginners. It includes extracting digits using the modulus operator inside a while loop.

# Python Program to Check Armstrong Number using While Loop

num = int(input("Enter a number: "))

# Store original number
original_num = num

# Find number of digits
n = len(str(num))

# Calculate sum of digits raised to power n
total = 0
while num > 0:
    digit = num % 10       # Extract last digit
    total += digit ** n    # Raise to power and add
    num //= 10             # Remove last digit

# Check condition
if total == original_num:
    print(f"{original_num} is an Armstrong number.")
else:
    print(f"{original_num} is not an Armstrong number.")

Output (input: 153):

153 is an Armstrong number.

Output (input: 123):

123 is not an Armstrong number.

How it works:

  • num % 10 extracts the last digit
  • num //= 10 removes the last digit after each iteration
  • len(str(num)) finds the total number of digits
  • We raise each digit to the power n and accumulate the sum.

Also Read: Python for Web Development

Method 2: Using a For Loop with String Conversion

This method converts the number to a string to iterate over each digit cleanly. It is slightly more Pythonic than the while loop approach.

# Python Program to Check Armstrong Number using For Loop

num = int(input("Enter a number: "))

# Count digits
n = len(str(num))

# Sum of each digit raised to power n
total = sum(int(digit) ** n for digit in str(num))

# Result
if total == num:
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

Output (input: 371):

371 is an Armstrong number.

Why this works well:

String iteration over digits is clean and readable. The sum() combined with a generator expression makes this a compact, one-liner-style calculation.

Method 3: Using a Function (Reusable and Clean)

It is a slightly more advanced way that can check Armstrong numbers multiple times in a program. You just have to give all the numbers with the program only, and it will test each number with the same logic.

# Python Program to Check Armstrong Number using a Function

def is_armstrong(num):
    """Returns True if num is an Armstrong number, False otherwise."""
    n = len(str(num))
    total = sum(int(digit) ** n for digit in str(num))
    return total == num

# Test the function
test_numbers = [153, 370, 371, 407, 9474, 123, 100]

for number in test_numbers:
    if is_armstrong(number):
        print(f"{number} is an Armstrong number.")
    else:
        print(f"{number} is not an Armstrong number.")

Output:

153 is an Armstrong number.
370 is an Armstrong number.
371 is an Armstrong number.
407 is an Armstrong number.
9474 is an Armstrong number.
123 is not an Armstrong number.
100 is not an Armstrong number.

Related Article: Python vs. R: What's the Difference?

Method 4: Find All Armstrong Numbers in a Given Range

This is an answer to one of the most asked Python interview questions, where they ask you to find out all the Armstrong numbers in a given range. Prepare this one, if you are going to attempt any interview soon.

# Python Program to Find All Armstrong Numbers Between 1 and 1000

def is_armstrong(num):
    n = len(str(num))
    return sum(int(d) ** n for d in str(num)) == num

lower = 1
upper = 1000

print(f"Armstrong numbers between {lower} and {upper}:")
armstrong_list = [num for num in range(lower, upper + 1) if is_armstrong(num)]
print(armstrong_list)

Output:

Armstrong numbers between 1 and 1000:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

Tip: This list comprehension approach is efficient and idiomatic Python. For very large ranges, consider adding early exit conditions or caching digit lengths.

Method 5: Using Recursion

Sometimes, you may be asked to not use loops. This is where you need to use the recursive approach. It is generally asked to check if the candidate have in-depth programming knowledge.

# Python Program to Check Armstrong Number using Recursion

def digit_power_sum(num, n, total=0):
    """Recursively calculates sum of digits raised to power n."""
    if num == 0:
        return total
    digit = num % 10
    return digit_power_sum(num // 10, n, total + digit ** n)

def is_armstrong_recursive(num):
    n = len(str(num))
    return digit_power_sum(num, n) == num

# Test
num = int(input("Enter a number: "))
if is_armstrong_recursive(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")

Output (input: 9474):

9474 is an Armstrong number.

Note: This method is an efficient one and will give you the right answer each time, but Python has a default recursion limit of 1000 calls. You should mention this with your answer.

Also Read: Introduction to CherryPy: A Python Web Framework

Wrapping Up

Armstrong numbers are a classic problem asked in interviews and assessments to test your understanding of loops, modular arithmetic and string-to-integer conversion in Python. This guide has already covered multiple important methods you can use. You should understand each code and try it yourself for better understanding. This way you will be one step closer to becoming a Python developer.

FAQs

Q1. Why is the Armstrong number used?

Armstrong numbers are used as an educational tool to teach foundational programming logic to beginners. They help students master essential concepts like loop structures, conditional statements and dynamic digit extraction.

Q2. What are the real-world applications of Armstrong numbers?

Armstrong numbers have no functional, real-world applications in commercial software development or data processing. They belong to recreational mathematics and are strictly used for academic training, coding interviews and hardware benchmarking.

Q3. Are all single-digit numbers Armstrong numbers?

Yes, all single-digit numbers (0–9) are Armstrong numbers by default. Because they contain only one digit, raising that single digit to the power of 1 always yields the original number itself.

Q4. What is the time complexity of checking an Armstrong number?

The time complexity is O(log10N), where N represents the input number. This is because the total number of operations scales linearly with the number of digits, which is logarithmic to the value of N.

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.