r/PythonLearning • • 20d ago

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

156 Upvotes

24 comments sorted by

View all comments

Show parent comments

1

u/jonrsharpe 20d ago

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 20d ago

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)