TracksPractical Coding FoundationsYour First Mini ProjectBuilding the Conversion Functions(4 of 11)

Building the Conversion Functions

With your plan ready, it's time to write code. Start with the core logic — the functions that actually convert numbers between bases. Python makes this surprisingly straightforward.

Python's Built-In Conversion Tools

Python provides built-in functions for base conversion:

  • bin(n) converts a decimal integer to binary
  • oct(n) converts a decimal integer to octal
  • hex(n) converts a decimal integer to hexadecimal
  • int(string, base) converts a string in any base to decimal

These functions do the heavy lifting. Your job is to wrap them in clean, easy-to-use functions.

Writing Wrapper Functions

The built-in functions add prefixes like 0b for binary and 0x for hexadecimal. Your wrapper functions can strip these for cleaner output:

def decimal_to_binary(n):
    return bin(n)[2:]  # Remove '0b' prefix

def decimal_to_octal(n):
    return oct(n)[2:]  # Remove '0o' prefix

def decimal_to_hex(n):
    return hex(n)[2:].upper()  # Remove '0x', uppercase

The [2:] slice removes the first two characters (the prefix). For hexadecimal, .upper() gives you uppercase letters like 2A instead of 2a.

Converting Back to Decimal

Converting from other bases to decimal uses int() with a base parameter:

def binary_to_decimal(binary_str):
    return int(binary_str, 2)

def octal_to_decimal(octal_str):
    return int(octal_str, 8)

def hex_to_decimal(hex_str):
    return int(hex_str, 16)

The second argument tells Python which base the input string is in.

Testing Each Function

Before moving on, test each function individually. This practice — testing small pieces before combining them — catches bugs early:

# Test decimal to other bases
print(decimal_to_binary(42))   # Should print: 101010
print(decimal_to_octal(42))    # Should print: 52
print(decimal_to_hex(42))      # Should print: 2A

# Test other bases to decimal
print(binary_to_decimal("101010"))  # Should print: 42
print(octal_to_decimal("52"))       # Should print: 42
print(hex_to_decimal("2A"))         # Should print: 42

Run these tests and verify the output matches your expectations. If something's wrong, fix it now while the code is simple.

Why Wrapper Functions Matter

You might wonder why we write wrapper functions instead of using Python's built-ins directly. Wrapper functions provide:

  • Cleaner output — No prefixes cluttering results
  • Consistent interface — All your functions work the same way
  • Easier changes — If you want different formatting later, change one place

This approach follows the principle of separation of concerns — each function has one clear job.

With your conversion functions working, you're ready to build the user interface that ties everything together.

See More

You need to be signed in to leave a comment and join the discussion