Trying to write code for converting decimal number into binary but it is showing output ending with "none" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Trying to write code for converting decimal number into binary but it is showing output ending with "none"

like if input is "4"....it is generating output as "100None" def D_to_B(n) binaryNum = [0] * n; i = 0; while (n > 0): binaryNum[i] = n % 2; n = int(n / 2); i += 1; for j in range(i - 1, -1,-1): print(binaryNum[j], end = ""); if __name__ == '__main__': n = int(input().strip()) result = D_to_B(n) print (result)

19th Sep 2022, 2:20 PM
vishwajeet pradip ghuge
vishwajeet pradip ghuge - avatar
9 Answers
+ 2
Here's an idea of implementation where D_to_B() returns a string forged by merging list elements https://code.sololearn.com/c5TM409HCwec/?ref=app + Added comments for explanation
19th Sep 2022, 3:52 PM
Ipang
+ 4
Remove last 2 lines. Just put D_to_B(n) You are not returning anything explicitly from function so implicitly it returns none. Don't catch it.
19th Sep 2022, 2:30 PM
Jayakrishna 🇮🇳
+ 3
Instead of printing reverse in function, return the result. And yes.. Instead of using list, better to use a string. binaryNum = "" and add by binaryNum += str( n%2 ) and your need return binaryNum reverse string is binaryNum[::-1]
19th Sep 2022, 2:53 PM
Jayakrishna 🇮🇳
+ 2
Adding to Jayakrishna - I would rather suggest you to try and find another way to do this - assuming it's for educational purpose such that you are not allowed to use built-in functions like bin() From data efficiency PoV, there's a lot of wasted memory using this approach. Try to convert 2048 to binary - you'll be creating a list with 2048 zeroes in,.while actually, 2048 can fit in just 12. I'm sure you understand ...
19th Sep 2022, 2:43 PM
Ipang
+ 2
Keeping the last block of code as it is, How can we made changes in above code so that this "None" problem can be solved? @jayakrishnain @Ipang
19th Sep 2022, 2:47 PM
vishwajeet pradip ghuge
vishwajeet pradip ghuge - avatar
+ 2
Did you mean to keep the code in __main__ or in the D_to_B() Minimum modification is as Jayakrishna stated - just call D_to_B(n) but don't pass it as argument for print() That way code works, with minimum revision. But I'd still rather suggest you find a better approach (algorithm) in doing this, for better plan of memory utilisation.
19th Sep 2022, 2:54 PM
Ipang
+ 2
First, add ":" in the function definition. Your function prints, so you essentially get a print(print()) ☺️ Debug: out = '' for j in range(i - 1, -1,-1): out += str(binaryNum[j]) return out
19th Sep 2022, 5:35 PM
Solo
Solo - avatar
0
Hello
20th Sep 2022, 4:23 PM
Kevin Engert
Kevin Engert - avatar
0
I'm new to all this
20th Sep 2022, 4:24 PM
Kevin Engert
Kevin Engert - avatar