简体   繁体   中英

Python: find sum of select digits

Sum of Specific Digits: Write a program using loops that gets an integer input from the user in the range 25030 and 999999 and finds the sum of the units digit, the hundreds digit and the ten-thousands digit. Make sure to use a loop to validate the input before you proceed to finding the sum of the

I tried but when the program inputs certain numbers it is off by 1:(

Try this, I used a try and except loop to catch errors

validinput=False
while not validinput:
    try:
        num=input("Input a number:")
        if 25030<=int(num)<=999999:
            validinput=True
        else:
            pass
    except:
        pass

unit=int(num[0])
hundred=int(num[2])
ten_thousand=int(num[4])
sum_of_digits=unit+hundred+ten_thousand
print(sum_of_digits)

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