Skip to content

Commit f079ad2

Browse files
committed
Add Error Handling
1 parent 889a61b commit f079ad2

File tree

1 file changed

+52
-34
lines changed

1 file changed

+52
-34
lines changed

ArmstrongNumber.py

Lines changed: 52 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,64 @@
11
# Authour: azmathias Stuperuser Ltd
22
# Purpose: Define a function that allows the user to check whether a given number is armstrong number or not.
33
# Number x, no of digits = n, if the sum of each digit raised to the power of n is equal to x, the number is an armstrong number (also called narcisstic numbers)
4-
# Notes: Examples of Armstrong Numbers are: 153, 407, 1634,
5-
# TODO: Add error handling if user does not enter a number.
4+
# Notes: Examples of Armstrong Numbers are: 153, 407, 1634
65

7-
testing_active = True
8-
9-
print("Armstrong Number Checker \n")
6+
# get number to test
7+
def inputNum(message):
8+
while True:
9+
try:
10+
userinput = int(input(message))
11+
except ValueError:
12+
print("\nPlease input a valid number:")
13+
continue
14+
else:
15+
return userinput
16+
break
1017

11-
try:
12-
while testing_active:
13-
num = input("Please enter a number:")
14-
num = int(num)
15-
16-
# calculate the length of the input number
17-
pownum = len(str(num))
18-
19-
sum = 0
20-
21-
# determine Armstrong number status
22-
resnum = num
23-
while resnum > 0:
24-
digit = resnum % 10
25-
sum += digit ** pownum
26-
resnum //= 10
18+
# determine Armstrong number status
19+
def armstrongNumcheck(number):
20+
pownum = len(str(number))
21+
sum = 0
22+
resnum = number
23+
while resnum > 0:
24+
digit = resnum % 10
25+
sum += digit ** pownum
26+
resnum //= 10
27+
# return results
28+
if number == sum:
29+
print(number,"is an Armstrong number")
30+
else:
31+
print(number,"is not an Armstrong number")
2732

28-
# return results
29-
if num == sum:
30-
print(num,"is an Armstrong number")
33+
# allow user to test again
34+
def testStatus():
35+
testQ = "\nType q to quit, or hit <Enter> to test another number."
36+
print(testQ)
37+
new_value = 0
38+
while not new_value:
39+
response = input('> ')
40+
if response == '':
41+
print()
42+
elif response == 'q':
43+
new_value = -1
3144
else:
32-
print(num,"is not an Armstrong number")
33-
34-
# test again?
35-
repeat = input("\nWould you like to test another number? (y/n) ")
36-
if repeat == 'n':
37-
testing_active = False
45+
print("\nPlease try again.")
46+
print(testQ)
47+
continue
48+
return new_value
3849

39-
break
40-
41-
except ValueError:
42-
print("Please enter a number: ")
50+
# program starts here
51+
def main():
52+
print("Welcome to the Armstrong Number Checker \n")
53+
value = 0
54+
while value != -1:
55+
num = inputNum("Please enter a number:")
56+
armstrongNumcheck(num)
57+
value = testStatus()
58+
print("\nThank you for playing!")
59+
4360

61+
if __name__ == '__main__': main()
4462

4563

4664

0 commit comments

Comments
 (0)