-1
def happy(num):
    while len(str(num))>1:
        finding=hfind(num)
    if finding==1:
        print("True")
    else:
        print("false")
    
def hfind(num):
    total=0
    for i in str(num):
        total+=int(i)*2
    num=total
    return(num)
    
happy(100)

I wrote code for Happy Number but,i don't know why it is not printing any output.

Can anybody explain clearly especially using this problem.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
NAIDU
  • 169
  • 7
  • 1
    It doesn't make any change because they are two different variables in disjoint scopes. Please do the expected work to trace your code's operation and values, and ask a *specific* question about what you don't understand. See this [lovely debugging site](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for help. – Prune May 04 '21 at 15:24

1 Answers1

0
  1. You need to reassign the value of num inside the loop.
  2. Use ** 2 to square a number.
  3. You need to check if the number reached 4 to prevent an infinite loop.
def happy(num):
    while num != 1 and num != 4:
        num = hfind(num)
    if num == 1:
        print("True")
    else:
        print("false")
    
def hfind(num):
    total=0
    for i in str(num):
        total += int(i) ** 2
    return total
    
happy(100)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80