File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ try :
3+ # Get input from the user.
4+ num = int (input ("Enter a number to check if it's an Armstrong number: " ))
5+
6+ # An Armstrong number must be positive.
7+ if num < 0 :
8+ print ("Please enter a positive integer." )
9+ else :
10+ # Convert the number to a string to find the number of digits (the order).
11+ s_num = str (num )
12+ order = len (s_num )
13+
14+ # Initialize the sum.
15+ sum_of_powers = 0
16+
17+ # A temporary variable to work with.
18+ temp = num
19+
20+ # Calculate the sum of each digit raised to the power of the order.
21+ while temp > 0 :
22+ digit = temp % 10
23+ sum_of_powers += digit ** order
24+ temp //= 10
25+
26+ # Check if the original number is equal to the sum.
27+ if num == sum_of_powers :
28+ print (f"{ num } is an Armstrong number." )
29+ else :
30+ print (f"{ num } is not an Armstrong number." )
31+
32+ except ValueError :
33+ print ("Invalid input. Please enter an integer." )
You can’t perform that action at this time.
0 commit comments