Home > Mobile >  Why is this code not working as intended? Python
Why is this code not working as intended? Python

Time:05-20

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??

CodePudding user response:

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.

CodePudding user response:

Your function only has one return statement, for the base case. You need a return for the recursive case, too.

When the recursion finishes, in your case the value is just thrown away because there's no return. Python isn't like other languages that return the value of the last expression. If there's no return statement, it returns None instead.

  • Related