0

Having difficulty to understand this code. Can somebody explain to me in a simple way.

# decimal to binary
def convert(num):
    if num == 0:
         return 0
    else:  
#explain this part          
     --> return (num % 2 + 10 * convert(num // 2)) <--
        
decimal = int(input())
print(convert(decimal))
  • 1
    What part don't you understand? – Patrick Haugh Apr 28 '22 at 04:48
  • @PatrickHaugh They have written a comment on that line. – Zero Apr 28 '22 at 04:49
  • @Ishan And what in there is unclear? The math? Recursion? Some specific syntax? – deceze Apr 28 '22 at 04:53
  • @PatrickHaugh The recursion, in this line: `num & 2 + 10 * convert(num//2)` Now, I don't understand how does this line work. As I try to understand the code, the recursion gives me more confusion. What's more confusing is the asterisk. Isn't * means multiply. – Joseph Tiglao Apr 28 '22 at 15:41
  • Yes, it multiplies 10 with the result of `convert(num//2)`. – deceze Apr 28 '22 at 15:43
  • FWIW, the `convert` function does _not_ convert decimal to binary. It converts a Python int `num` to another int such that the decimal string representation of that int matches the binary string representation of `num`. That's quite an unnatural thing to do. – Mark Dickinson May 03 '22 at 14:16

0 Answers0