Python Forum

Full Version: summing digits of a number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've a problem with my code
get a number from user then summing digits of that number

num = input()
y = 0
for x in range(0, len(num)):

    y = int(num[x:x+1]) + int(num[x+1:x+2]) + y

print(y)
i cant finger out what's the problem
(my native language isn't English so may i have some mistakes)
(Jun-29-2018, 06:37 AM)Megabeaz Wrote: [ -> ]I've a problem with my code
get a number from user then summing digits of that number

num = input()
y = 0
for x in range(0, len(num)):

    y = int(num[x:x+1]) + int(num[x+1:x+2]) + y

print(y)
i cant finger out what's the problem
(my native language isn't English so may i have some mistakes)


it was solved
i changed it to:
num = input()
if len(num) == 1:
    print(num)
else:
    while True:
        n_1 = int(num[:1])
        for x in range(1, len(num)):
            try:
                n_1 = int(num[x:x + 1]) + n_1

            except:
                n_1 = int(num[x:]) + n_1
        if len(str(n_1)) == 1:
            break
        else:
            num = str(n_1)
    print(n_1)
it's a program for summing digits of a number til
the number reach to one digit
Now, that you have solved it - let me show you a Pythonic solution (works on 3.x only)

def sum_digits(number):
    digits_sum = 0
    while number:
        digit, *number = number
        digits_sum += int(digit)
    return digits_sum

PS Actually, while is less suitable than for in this case
def sum_digits(number):
    digits_sum = 0
    for digit in number:
        digits_sum += int(digit)
    return digits_sum
or in the shortest form, just
sum(map(int, number))
The latter, of course, takes time to get used to - unless you are a mathematician Tongue
The reason volano63's solutions are preferred is that it's better to loop directly over a string or list than to loop over the indexes of that string or list.

Another couple tips:

# These two ranges are the same
x = range(0, 6)
y = range(6)

# These two references are the same
a = s[x:x+1]
b = s[x]