English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python Program to Check Armstrong Number

Python example大全

In this example, you will learn to check if an n-digit integer is an Armstrong number.

To understand this example, you should understand the followingPython programmingTopic:

A positive integer is called an Armstrong order, n if

abcd... = an + bn + cn + dn + ...

If it is3If a number is an n-digit Armstrong number, the sum of the cubes of each digit is equal to the number itself. For example:

153 = 1*1*1 + 5*5*5 + 3*3*3  // 153is an Armstrong number.

Source code: Check Armstrong number (3digit)

# Check if the number is an Armstrong number using Python
# Accept user input
num = int(input("Enter a number: "))
# Initialize sum
sum = 0
# Calculate the sum of the cubes of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10
# Display the result
if num == sum:
   print(num, "is an Armstrong number")
else:
   print(num, "is not an Armstrong number")

Output1

Enter a number: 456
456 Is not an Armstrong number

Output2

Enter a number: 407
407 Is an Armstrong number

Here, we ask the user to enter a number and check if it is an Armstrong number.

We need to calculate the sum of the cubes of each digit. Therefore, we initialize the sum to 0 and usemodulus operator (%))to get each digit. Divide the number by10The remainder obtained is the last digit of the number. We use the exponent operator to get multidimensional datasets.

Finally, we compare the sum with the original number to draw a conclusion. If they are equal, it is an Armstrong number.

Source code: Check if n-digit number is an Armstrong number

num = 1634
# Change the num variable to a string
# And calculate the length (number of digits)
order = len(str(num))
# Initialize sum
sum = 0
# Calculate the sum of the cubes of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10
# Display the result
if num == sum:
   print(num, "is an Armstrong number")
else:
   print(num, "is not an Armstrong number")

You can change the value of num in the source code and run it again to test it.

Python example大全