Home > OS >  How can I print all values that are true according to the statement provided
How can I print all values that are true according to the statement provided

Time:10-12

so I programmed my code in a way that whenever an input number is given, the output will always only display '1' or '4' after squaring each digit of the number AND adding the values of the squared digits together. Here is my code,

number = int()
sum_of_digits = 0
x = ''
while x not in ['1', '4']:
    for digit in str(number):
       sum_of_digits  = (int(digit)**2)
    x = str(sum_of_digits)
    number = sum_of_digits
    sum_of_digits = 0
print(x)
def IsHappy(x):
    if x == '1':
        return 'True'
    else:
        return 'False'

So basically once you run my code, you will get either 1 or 4 and True or False, 1 being true and 4 being false, now what I want to do is to define a variable that will print out ALL NUMBERS (yes infinitely many numbers) that satisfy the condition 'True', how can I do that??

CodePudding user response:

Put the code that calculates the sum of digits in a function. You can then call the function in a loop.

def get_sum_of_digits(number):
    x = ''
    while x not in ['1', '4']:
        sum_of_digits = sum(int(digit)**2 for digit in str(number))
        x = str(sum_of_digits)
    return x

def IsHappy(x):
    if x == '1':
        return 'True'
    else:
        return 'False'

for i in range(100):
    if IsHappy(get_sum_of_digits(i) == 'True'):
        print(i)
  • Related