+ 1
Recursion from decimal to binary
The task is: 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. https://code.sololearn.com/cdo9ScG7h2v3/?ref=app Actually, my code is pretty much exactly the Sololearn solution. Why is there no output?
8 Answers
+ 2
After return you leave the function.
Anyway...some guys prefer if else construct. It might be a bit safer.
+ 2
You might want to look at it again. Outdenting line 4 seems to fix the problem (got output). Though I haven't tested it using many numbers.
+ 1
Only return 0 should run if num==0, the recursive step needs an else-path.
+ 1
If that is their suggested solution then yes it is incorrect. Perhaps you find the time to report the error so that it can be fixed.
+ 1
Ani Jona đ no.... else is not required.
Ipang that's it. Decent line 4.
+ 1
Why is the else actually not needed here?
0
Thanks. So the Sololearn solution is wrong hereâŠ
0
#If statement will add the base case. You must include the else statement, otherwise it will print None.
def convert(num):
if num == 0:
return 0
else:
return (num % 2 + 10 * convert(num // 2))
num = int(input())
print(convert(num))