0

I'm a beginner on python and I want to know how can I sum digits for a random number between 1-10000 Print the number is easy:

from random import randint

x = randint(1, 10001)

print x

but how can I sum the number of digit of the outcome, Thanks,

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
Meirshalom
  • 31
  • 3
  • One of the many ways: convert to string, split into array, map to `int`, then `sum`. – Andrew Li May 26 '17 at 17:06
  • 2
    Possible duplicate of [Sum the digits of a number - python](https://stackoverflow.com/questions/14939953/sum-the-digits-of-a-number-python) – Alex K. May 26 '17 at 17:10

1 Answers1

1

I hope this will answer your question.Convert the number to string and parse digit by digit.

from random import randint
x = randint(1, 10001)
print x
sum = 0
for i in str(x):
    sum += int(i)
print sum
mssnrg
  • 96
  • 3