My original python program used string interpolation to take a number a user enters between 0-9999 like 2928, and summed its individual digits (2+9+2+8=21), and then split the number until eventually it became a single digit number (in this case 3), which was displayed on the screen. The code looks like this:
Now I am needing to figure out a way to do the same without using string interpolation(converting the integers to strings and then splitting the strings, reconverting them to integers, and summing them). I am fairly new to python and therefore can use very simple commands (most complex being the while loop) can anyone help me out/ throw me some ideas?
*ps, I guess some ambiguity exists as to what yearint- year is. “year” is a command that i didnt write above but its code makes the user enter a number between 0-9999. I changed its variable name to “yearint” because I am new to python and want to make things descriptive so I can remember them when I look back. SO basically year/yearint are the input the user inputs.
I am typing this on a mobile phone, so I will use ” y ” instead of ” yearString “.
See how, if the sum has multiple digits, a later if statement will handle it. Now let’s write similar code using pure math:
EDIT: Now that I have thought about it, I think I see the best way for you to do this. I will not write the full code for this.
If you use the modulus operator by 10 you pull out the bottom digit. Then if you use integer division by 10, you remove the bottom digit. Do this in a while loop and keep doing it until you have all the digits out; the number will be zero after the last divide by 10. Make a function that does this, and call it from a while loop until the sum is less than 10 (is a single digit).
EDIT: Okay, I guess I might as well write the full code: