+ 1

# 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))

11 Answers

+ 8

hello 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())))

+ 1

"""
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())))

+ 1

pardeep
Is this the code provided to you, or is it your attempt?

+ 1

def convert(num):
if num==1:
return 1
else:
return (num % 2 + 10 * convert(num // 2))
print(convert(int(input())))

0

Can you attach the code for us to look at

0

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

0

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))
where does this 10 come from?

0

def convert(num):
if num==0:
return 0
return (num % 2 + 10 * convert(num // 2))
a=int(input())
print(convert(a))

0

def convert(num):
if num == 1.0:
return True
else:
return (num % 2 + 10 * convert(num // 2))
num =int(input())
print(convert(num))

- 1

sorry about not posting code,,, now it is updated

- 1

it is a question provided to me