Print all Armstrong Numbers in Python
Enter lower bound: 100
Enter upper bound: 9999
153, 370, 371, 407, 1634, 8208, 9474,
from math import floor, log
def main():
"""
Prints all the Armstrong numbers within a given range.
"""
# Get the lower and upper bounds
a = int(input("Enter lower bound: "))
b = int(input("Enter upper bound: "))
# Print all the Armstrong numbers
for i in range(a, b + 1):
if is_armstrong(i):
print(i, end=", ")
print()
def is_armstrong(number: int):
"""
Checks if a number is an Armstrong number or not.
"""
# Check if the number is positive
if number < 0:
return False
BASE = 10
# Find the total number of digits
count = number_length(number, BASE)
# Calculate the sum of the digits
total = 0
n = number
while n != 0:
unit_digit = n % BASE
total += unit_digit**count
n //= BASE
return total == number
def number_length(number: int, base: int):
"""
Returns the number of digits in a number.
"""
number = abs(number)
return floor(log(number, base)) + 1 if number != 0 else 1
if __name__ == "__main__":
main()