简体   繁体   中英

calculate the sum of the digits of any three digit no(in my code loop is running every time help in correction)

my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6 this is the problem there is logical error in program .Help in resolving it` this is the complete detail of my program

i have tried it in this way

**********python**********

while(1):
    a=int(input("Enter any three digit no"))

    if(a<100 or a>999):
        print("enter no again")
    else:
        s = 0
        while(a>0):
            k = a%10
            a = a // 10
            s = s + k
            print("total",s)

there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123 total=6 but im getting total=3 then total=5 and in last total=6 one line of output is coming in three lines

If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.

import re
while True:
  num = input("Enter number:  ")
  match = re.match(r"^\d{3}$, num)
  if match:
     numList = list(num)
     sum = 0
     for each_number in numList:
         sum += int(each_number)
     print("Total:", sum)

  else:
     print("Invalid input!")

Additionally, you can verify via exception handling, and implementing that math you had instead.

while True:
  try:
      num = int(input("Enter number:  "))
      if num in range(100, 1000):
          firstDigit = num // 10
          secondDigit = (num // 10) % 10
          thirdDigit = num % 10
          sum = firstDigit + secondDigit + thirdDigit
          print("Total:", sum)
      else:
          print("Invalid number!")
  except ValueError:
     print("Invalid input!")

Method two utilizes a range() function to check, rather than the RegEx.

Indentation problem dude, remove a tab from last line.

Also, a bit of python hint/tip. Try it. :)

a=123
print(sum([int(x) for x in str(a)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM