help in hoemwork - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: help in hoemwork (/thread-2763.html) Pages:
1
2
|
help in hoemwork - maayan11 - Apr-08-2017 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 :) RE: help in hoemwork - micseydel - Apr-08-2017 What have you tried? RE: help in hoemwork - ichabod801 - Apr-08-2017 Look at the modulus operator % and the integer division operator // .
RE: help in hoemwork - harrington40 - Apr-08-2017 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? RE: help in hoemwork - ichabod801 - Apr-08-2017 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. RE: help in hoemwork - maayan11 - Apr-08-2017 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
RE: help in hoemwork - ichabod801 - Apr-08-2017 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 = totalNow 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. RE: help in hoemwork - maayan11 - Apr-09-2017 thank you/ but if im writing for exemple thatfunction on the number 74 it will give me 11 and not 2 (1+1) RE: help in hoemwork - wavic - Apr-09-2017 Do recursion. RE: help in hoemwork - maayan11 - Apr-09-2017 Ive tried:\ it doesnt going well for me |