Why is this code not working as intended? Python

import string

decimal1 = 55
binary1 = 0

def convert(decimal1, binary1):
    binary1 = str(decimal1 % 2) + str(binary1)
    decimal1 = decimal1//2
    if decimal1 == 0:
        binary1 = str(binary1)
        return binary1
    convert(decimal1, binary1)
x = convert(decimal1, binary1)
print(x[-1])

I wanted a code that converts decimal to binary but the function output is not being taken into x or the program is the returning none. I want to understand why it is happening??

>Solution :

I think if you want to reteurn the result, then you don’t need to pass binary1 variable.

import string

decimal1 = 55

def convert(decimal1):
    value = str(decimal1 % 2)
    decimal1 = decimal1//2
    if decimal1 == 0:
        return value
    else:
        return convert(decimal1) + value


x = convert(decimal1)
print(x)

Hope it could help.

Leave a Reply