-2

I'm a newbie and this is my first stupid question on StackOverflow. Would anybody let me know why line 7 was executed while the condition is false (input = 1)? This is the screenshot Thanks a lot and all the best to you!

print("line 1 - START OF CODE - right before function 'def decimalToBinary(num)' \n", "line 2-9 - define function 'decimalToBinary(num)'")
def decimalToBinary(num):
    print("\n Line 2 - execute the function 'decimalToBinay(num)'' \n Line 3 - right before if statement - at this line num value is:", num, ", var number is:",number,"\n")
    if num > 1:
        print("Line 4-5 - 'if statement' is true (num > 1), num value is", num, "> 1", "\n Line 6 - recall function 'decimalToBinary(num // 2)' \n")
        decimalToBinary(num // 2)
        print("Line 7 - 'if statement' end - This is num after line 6 'decimalToBinary(num // 2)'. Num is",num)
    print("Line 8 - This is num before the line 'print(num % 2)':", num)
    print("Line 9 - This is result of num % 2:", num % 2, "\n")
number = int(input("line 10 - Ask user 'Enter any decimal number:' then assign this value to var 'number' \n line 11 - call function 'decimalToBinary(number)': "))
decimalToBinary(number) #function call
print("line 12 - END OF CODE")
Louis
  • 1
  • 3

2 Answers2

0

From my understanding of your question, your assumption is if the input is 2, then if num > 1, will run of course. And then it goes to decimalToBinary(num//2). However, to do that you need to change line 6 to return decimalToBinary(num//2)

Zichzheng
  • 1,090
  • 7
  • 25
0

You need to RETURN something from your function. Then, as the recursion returns, you need to add this (least significant) digit to what you got from the parent.

def decimalToBinary(num):
    s = ''
    if num > 1:
        s = decimalToBinary(num // 2)
    return s + str(num%2)
number = int(input("Enter any decimal number:"))
print(decimalToBinary(number))
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30