Reputation:
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
Upvotes: 0
Views: 1286
Reputation: 16556
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)
Upvotes: 0
Reputation: 82530
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.
Upvotes: 0
Reputation: 30136
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
Upvotes: 6