简体   繁体   中英

Sum of digits of a number using While

How can I do the sum of numbers that was given on a function? Like this: def sum (123)
How can I make python sum 123 to give 6 using while?

def calc_soma(num):
    ns = str(num)
    soma = 0
    while soma < len(ns):
        soma = eval(ns[soma])
        soma = soma + 1
    return soma

I tried this but it doesn't work. I'm new on python so i don't no many things

Why do you convert it to a string when you can simply get each digit from the integer?

while num > 0:
    soma += num%10
    num /= 10

Basically you mod it:

>>> total = 0
>>> num = 123
>>> while num > 0:
...     total += num % 10
...     num /= 10
...
...
>>> total
6

You could use str , but that would be slow.

You are using soma to hold indices AND the result. Here is a modified version:

>>> def calc_soma(num):
...     ns = str(num)
...     soma = 0
...     indic = 0
...     while indic < len(ns):
...         soma += int(ns[indic])
...         indic = indic + 1
...     return soma
...
>>> calc_soma(123)
6
>>> calc_soma(1048)
13

If you want to iterate over the str , you can use list comprehension:

>>> sum([int(i) for i in str(123)])
6
>>> sum([int(i) for i in str(2048)])
14

You can also get rid of the [/] :

sum(int(i) for i in str(123))

(Also, check barak manos's answer. You can "mathematically" do that)

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