Armstrong number shows wrong output twice and correct at the end (Python)

x = int(input("enter your number"))
f = x 
sum_ = 0
while(f>0):
    a =f % 10
    f = int(f//10)
    sum_ =sum_ + (a**3)
    if (x == sum_):
        print("it is armstrong")
    elif (x!= sum_):
        print(x,"is not an armstrong number") 

When I run this code, I get the following output:

enter your number153
153 is not an armstrong number
153 is not an armstrong number
it is armstrong

Why does it show incorrectly two times, and the correct output once at the end? How can I fix this?

Upvotes: 0

Views: 86

Answers (4)

cards
cards

Reputation: 4990

A functional programming approach.

def is_amstrong(n):
    return n == sum(map(int(3).__rpow__, map(int, str(n))))

# test: all amstrong numbers less than 1000
for i in range(9999):
    if is_amstrong(i):
        print(i)

Output

0   # <- trivial case
1   # <- trivial case
153
370
371
407

By adding a check on the input number, such as n>1, the trivial cases can be avoided.

Upvotes: 0

Daniel Hao
Daniel Hao

Reputation: 4980

As previous post has pointed out, the if-loop should be put in outside of the while loop to avoid the double print.

Alternatively, you can make this into a function to be used later:

def is_armstrong(n: int) -> bool:
    num = str(n)
    powered = len(num)

    return n == sum(int(x)** powered for x in num)


if __name__ == '__main__':
     nums = [153, 371, 456]

     for num in nums:
         print(f' {num} is an armstrong? {is_armstrong(num)} ')

     # or calling by asking user input:
     # x = int(input('Type a number to check: '))
     # print(is_armstrong(x))


# 153  True
# 371  True
# 456  False

Upvotes: 1

Your if condition is continuously being checked for each digit in the input number. You'll need to write the if condition outside the loop, to have it checked only once.

corrected code:

x=int(input("enter your number"))
f=x 
sum=0
while(f>0):
    a=f%10
    f=int(f//10)
    sum=sum+(a**3)
if (x==sum):
    print("it is armstrong")
elif (x!=sum):
    print(x,"is not an armstrong number")

Note that your condition was just unindented one level to make it outside your loop.

Upvotes: 0

Daniel Paul
Daniel Paul

Reputation: 514

put the if condition outside the while loop.

x=int(input("enter your number"))
f=x 
sum=0
while(f>0):
    a=f%10
    f=int(f//10)
    sum=sum+(a**3)
if (x==sum):
   print("it is armstrong")
elif (x!=sum):
   print(x,"is not an armstrong number")

Upvotes: 0

Related Questions