hello:)
in my home work I need to write a code that sum the digits of number.
for example if the original number is 563 the function will return- 5 (5+6+3=14 4+1=5)
can you help me in this question?
thank you :)
Look at the modulus operator %
and the integer division operator //
.
I will work with you to solve this problem, however, I will require your commitment ... if you agree
let me know .. committing to explain why you think it is difficult?
We don't think it's difficult. We just don't want to write your code for you. You try something, you show us what you tried, you tell us how it's not working, and we will be happy to help you fix it.
I am, however, 47 and single, so I'm obviously afraid of commitment.
ok this is what i tried but Ive got a note that iindex out of range
def finaldigits(num):
b=0
while b==0 or b>9:
i=0
for i in range(len(str(num))):
b+=int(str(num)[i])
num=b
return num
Moderator Larz60+: And use code tags
You don't need to initialize i, the loop does that for you. Also, single letter names are a bad habit to get into, they make more complicated programs harder to understand. Use descriptive words. Also, it's better to loop directly over something, rather than loop over indices of that thing:
total = 0
for char in str(num):
total += int(i)
num = total
Now you're not doing any indexing, so you shouldn't have any index errors. Looping over a string (like str(num)) gives one character of the string each iteration of the loop. I dedented num, since you only need to do that once at the end of the for loop, not each time through the for loop.
thank you/
but if im writing for exemple thatfunction on the number 74 it will give me 11 and not 2 (1+1)
Ive tried:\ it doesnt going well for me