Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help in hoemwork
#1
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 :)
Reply
#2
What have you tried?
Reply
#3
Look at the modulus operator % and the integer division operator //.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
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?
Reply
#5
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
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
Reply
#7
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
thank you/
but if im writing for exemple thatfunction on the number 74 it will give me 11 and not 2 (1+1)
Reply
#9
Do recursion.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
Ive tried:\ it doesnt going well for me
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020