# recursion python question

The given code defines a recursive function convert(), which needs to convert its argument from decimal to binary. However, the code has an error. Fix the code by adding the base case for the recursion, then take a number from user input and call the convert() function, to output the result. Sample Input: 8 Sample Output: 1000 def convert(num): return (num % 2 + 10 * convert(num // 2))

3/14/2021 9:05:26 AM

pardeep7 Answers

New Answerhello pardeep , did you solve the question? if not then here is the code: # you need to provide base case then call the function with an input to allow client interaction def convert(num): if num==1: return 1 else: return (num % 2 + 10 * convert(num // 2)) print(convert(int(input())))

""" you don't provide at least the base code to be fixed, but this one works: """ def convert(n,s=''): if n==0: return s or '0' return convert(n//2,str(n&1)+s) print(convert(int(input())))

just provide the base condiation in which the function is evaluated and it is done by using if statements condaition. if the num is zero then the if condiation result return a zero and other wise it will return the (num % 2 + 10 * convert(num // 2)) expression def convert(num): if num == 0: return 0 else: return (num % 2 + 10 * convert(num // 2)) a = int(input()) print(convert(a))