So I was given a variable n, and I had to find the value OF EACH DIGIT in the number, square them, and add it together. For example, if n = 145, so (1^2) (4^2) (5^2) = 42 and the same process repeats until one of the digits is either 1 or 4. How can I do that??
number = 145
sum_of_digits = 0
for digit in str(number):
sum_of_digits = (int(digit)**2)
print(sum_of_digits)
This is my code so far.. It successfully squares and adds every single digit in the number but it doesn't repeat until either one of the digits is 1 or 4... so what am I supposed to do?
if you dont understand my question, please look in the comment section below, I tried to explain my question again there.
CodePudding user response:
You can create while True
and check ['1','4']
in the result and break like below:
while True:
number = input()
sum_of_digits = 0
for digit in number:
sum_of_digits = (int(digit)**2)
print(sum_of_digits)
if any(i in str(sum_of_digits) for i in ['1','4']):
break
You can shorted code like below:
while True:
number = input()
sum_of_digits = sum(int(digit)**2 for digit in number)
print(sum_of_digits)
if any(i in str(sum_of_digits) for i in ['1','4']):
break
Output:
889
209
145
42
CodePudding user response:
I think what you need is this:
number = 145
sum_of_digits = 0
while True:
for digit in str(number):
sum_of_digits = (int(digit)**2)
if '1' in str(sum_of_digits) or '4' in str(sum_of_digits):
break
print(sum_of_digits)