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

Tutorial básico do Python

Controle de fluxo no Python

Funções do Python

Tipos de Dados do Python

Operações de arquivos no Python

Objetos e classes no Python

Data e hora no Python

Conhecimentos avançados do Python

Manual de referência do Python

Verificação de número Armstrong em programas Python

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  // 153It is an Armstrong number.

Source code: Check Armstrong number (3digit)

# Check if the number is an Armstrong number in Python
# Accept user input
num = int(input("Enter a number: "))
# Initialize sum
sum = 0
# Calculate the sum of cubes of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10
# Show 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 cubes of each digit. Therefore, we initialize the sum to 0 and useModulus operator (%))Get each digit. Divide the number by10The remainder is the last digit of the number. We use the exponent operator to get multidimensional data sets.

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 string
# And calculate the length (number of digits)
order = len(str(num))
# Initialize sum
sum = 0
# Calculate the sum of cubes of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10
# Show 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大全