r/PythonLearning • • Oct 02 '26 • Bravo 1

just finished my first Python coding challenge

Post image

Today I finished a small Python challenge on freeCodeCamp: converting decimal numbers to binary without using Python's built-in conversion function.

I had to figure out the logic myself using loops, conditions, lists, division and remainders.

It was a bit tricky at first, especially handling the last division and reversing the results, but I finally got it working.

I'm still a beginner, so I'd appreciate any feedback on my approach or suggestions for improving my code

158 Upvotes

24 comments sorted by

•

u/Sea-Ad7805 Oct 02 '26

Run this program by clicking Memory Graph Web Debugger and see its state change step by step.

→ More replies (1)

2

u/therouterguy Oct 02 '26

I would at least change the elif to an else. Remove the duplicate decimal=decimal//2. You can do it outside of the if

Lastly
tab=“”
while decimal!=O:
tab=tab + “1” if decimal%2==O else tab+ “0”
decimal=decimal//2
Is much shorter

1

u/jonrsharpe Oct 03 '26 edited Oct 03 '26

I'm going to start with where I'd get to, then break down step-by-step how I got there:

def to_binary(decimal: int) -> str:  
    digits: list[str] = []  
    while decimal:  
        decimal, remainder = divmod(decimal, 2)  
        digits.append(str(remainder))  
    return "".join(reversed(digits))  

1

u/jonrsharpe Oct 03 '26 edited Oct 03 '26

Firstly, I added the type hints - partly just to document what I was working out about the code as I read it (receives an integer, has a list of integers, returns a string) but also because these can then be automatically checked and provide a kind of documentation to the caller. (Note that these are not enforced by Python itself, but type checkers, like mypy, and IDEs can use them.)

1

u/jonrsharpe Oct 03 '26 edited Oct 03 '26

This highlighted that decimal on the penultimate line, as well as "shadowing" the parameter, changes the type this name refers to (it was an integer, now a string). But that's also the wrong name - that's no longer in decimal format, it's the binary format we are about to return, so I renamed it accordingly.

1

u/jonrsharpe Oct 03 '26

After that I reformatted the file according to the Python style guide, PEP-0008. Whitespace around expressions was, worse than being unconventional, inconsistent (compare decimal = decimal//2 with decimal = decimal //2).

1

u/jonrsharpe Oct 03 '26

Next the logic: decimal = decimal // 2 appears in two places, so can be moved outside the conditional, and simplified using the in-place operator to decimal //= 2.
I also considered simplifying to else, as if decimal % 2 isn't 0 there's only one other option, but at this point it should be really clear that we can simplify further than that by just appending the remainder:

        if decimal % 2 == 0:
            tab.append(0)
        elif decimal % 2 == 1:
            tab.append(1)

to:

        tab.append(decimal % 2)

0

u/[deleted] Oct 03 '26

[removed] — view removed comment

1

u/jonrsharpe Oct 03 '26

Rather than reverse the list in-place, we can use reversed to create a new list with the elements in reverse order. As this no longer returns None, it can be inlined - the temporary variable can be factored out too, making the last line outside the loop simply return "".join(reversed(digits)).

1

u/jonrsharpe Oct 03 '26 edited Oct 03 '26

Given that we want both x // y and x % y (the remainder of the integer division), note the built-in divmod function provides both simultaneously. It returns a tuple of two values, which Python lets you "unpack" into two variables as follows:

decimal, remainder = divmod(decimal, 2)

1

u/FunResearcher6290 Oct 03 '26

please how can i go about it i want learn python

1

u/codeguru42 Oct 03 '26

Looks great. One hint: how can you change the code to remove the if statement?

1

u/kaatarina_zed_talon Oct 05 '26

This is problem solving, not a python coding challenge, python is just a tool.

1

u/Expensive-Pen7038 Oct 06 '26

Isn't all python coding problem solving?

1

u/ConclusionForeign856 Oct 02 '26

Read about truthy and falsy values in python, it allows you to simplify logic

def binary(n: int):
    tab = []
    while n:
        remainder = n % 2
        n //= 2
        tab.append(remainder)

    return ''.join(map(str, tab[::-1]))

-2

u/Adrewmc Oct 02 '26

Great practice… however the builtin ‘bin()’ function exists, so next time you can just use that.

0

u/codeguru42 Oct 03 '26

This is a learning exercise

1

u/fizzy_lychee Oct 03 '26

So? I still appreciated knowing there’s an api for bloom sort even though I’ve implemented my own version. I still appreciated languages that have hasmaps in their SDK even though I’ve created my own in C.

0

u/gofl-zimbard-37 Oct 02 '26

Give it a proper main() and call it. Don't write "scripts". The file is main.py, implying that it is a module that exports useful functions. Nobody wants an import to be printing stuff out.

-1

u/AffectionateCold1716 Oct 02 '26

I’m still new so I have no idea what this means but I do recognize you defining a function and calling the function. Sooooo yep. Anyway good job compadre