Another interesting way to resolve this issue is to associate Assignment expressions along with Generating expressions.
In this case the code would be:
x = input("Digite um número: ")
while (s := sum(int(i) for i in x)) > 9:
x = str(s)
print(f'O resultado é: {s}')
Note that this code captures digits in the string format. Next, the generating expression will be responsible for calculating the sum of all digits of the converted integer string. Later, the block while check whether the outcome of the expression of assignment associated with the variable s is greater than 9. If yes, the value of x will be updated as the s and the generating expression will be executed again, only this time with the new value - which is the string of s.
Note that while the value assigned to the assignment expression is greater than 9, calculations will be redone. Otherwise, the repeat loop while is closed and the value will be displayed.
Testing the code:
Imagine that when executing the respective code we typed the value:
155
The code would be executed and provide us with the value 11. For...
1 + 5 + 5 = 11
Now, how 11 is greater than 9, the generating expression will be executed again, producing as a result the value 2. For...
1 + 1 = 2
Since 2 is less than or equal to 9, the loop is closed by displaying the value as a result 2.
Another interesting way to resolve this issue is to apply the concepts of
Proof of the Nine Out, performing a SUBTLE amendment to the final reply. This amendment replaces the final result with 9, if the same is 0.
Why this amendment?
The proof of the nine out is nothing more than the rest of the entire division of an "n" number by 9. Thus, if an "n" number is a multiple of 9, soon the rest of the division will be 0. Only by the logic of your code, answers will only be allowed between 1 and 9. So if the result of the nine out is 0 we should replace it with 9.
OBSERVING: If the entered value is None - empty - the program must return the value 0.
With this logic we can implement the following code:
def digital_root(n):
return 0 if not n else 9 if (r := n % 9) == 0 else r
if __name__ == '__main__':
number = int(input())
resp = digital_root(number)
print(resp)
Note that this code captures the entered value and checks whether it is None. Positive case, returns 0. If not, calculate the rest of your division by 9. If the value of the assignment expression assigned to the variable r be it 0 the value will be replaced by 9. Otherwise, the variable value r will be shown.
NOTE:
THIS ISSUE WAS MADE AVAILABLE BY CODEWARS PLATFORM, whose link is: Sum of Digits / Digital Root
Choose one of the solutions of this question and keep repeating this until the sum is less than 10
– hkotsubo
That’s exactly what I did, but the first while doesn’t work.
– Joao Pedro Oliveira Prado