YouTip LogoYouTip

Python3 Armstrong Number

# Python3.x Python Armstrong Number [![Image 3: Document Object Reference Manual](#) Python3 Examples](#) If an **n**-digit positive integer equals the sum of the **n**th powers of its digits, it is called an Armstrong number. For example, 1^3 + 5^3 + 3^3 = 153. Armstrong numbers within 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407. The following code is used to check if a user-input number is an Armstrong number: ## Example (Python 3.0+) # Filename : test.py# author by : www..com# Python checks if the user-input number is an Armstrong number# Get user input number num = int(input("Please enter a number: "))# Initialize variable sum sum = 0# Exponent n = len(str(num))# Check temp = num while temp>0: digit = temp % 10 sum += digit ** n temp //= 10# Output result if num == sum: print(num,"is an Armstrong number")else: print(num,"is not an Armstrong number") Executing the above code outputs: $ python3 test.py Please enter a number: 345345 is not an Armstrong number $ python3 test.py Please enter a number: 153153 is an Armstrong number $ python3 test.py Please enter a number: 16341634 is an Armstrong number ### Get Armstrong numbers within a specified range ## Example (Python 3.0+) # Filename :test.py# author by : www..com# Get user input numbers lower = int(input("Minimum value: "))upper = int(input("Maximum value: "))for num in range(lower,upper + 1): # Initialize sum sum = 0# Exponent n = len(str(num))# Check temp = num while temp>0: digit = temp % 10 sum += digit ** n temp //= 10 if num == sum: print(num) Executing the above code outputs: Minimum value: 1Maximum value: 10000123456789153370371407163482089474 In the above example, we output the Armstrong numbers between 1 and 10000. [![Image 4: Document Object Reference Manual](#) Python3 Examples](#)
← Python3 If ExamplePython3 Celsius Fahrenheit β†’