I have recently started to code in Python. While trying to solve a problem statement I encountered this issue where my code does not return the value. The code is to continue adding all the digits in the number given, until you get a value less than or equal to 9.
Example : 12345->1 2 3 4 5=15. 15 is greater than 9 so 1 5=6. 6 is less than 9 so 6 should be returned. Here's the code:
def uno(num):
temp=str(num)
sum1=0
for x in temp:
sum1=sum1 int(x)
print(sum1)
if sum1<=9:
return sum1
else:
uno(sum1)
result=uno(12345)
print(result)
Output:
15
6
None
The output I get is 'None'. I tried to debug using "print(sum1)". The value is stored as expected. Can you please tell me where I made a mistake.
CodePudding user response:
You forgot a return
statement:
def uno(num):
temp = str(num)
sum1 = 0
for x in temp:
sum1 = sum1 int(x)
if sum1 <= 9:
return sum1
else:
return uno(sum1)
result = uno(12345)
print(result)
Output
6
CodePudding user response:
In the else statement, write:
return(uno(sum1))