Andre Kramer
Andre Kramer

Reputation: 11

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 :(

Upvotes: 0

Views: 274

Answers (1)

Bob
Bob

Reputation: 236

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)

Upvotes: 1

Related Questions