Write a Python function to convert a decimal number to binary.
Posted by CarolTh
Last Updated: August 29, 2024
Converting a decimal number to binary in Python can be accomplished using a simple function. Here's a straightforward implementation:
def decimal_to_binary(n):
    """
    Convert a decimal number to binary representation.

    Parameters:
    n (int): A decimal integer to be converted.

    Returns:
    str: Binary representation of the input decimal number.
    """
    if n < 0:
        raise ValueError("Input must be a non-negative integer.")
    
    # Special case for zero
    if n == 0:
        return "0"
    
    binary_digits = []
    
    while n > 0:
        binary_digits.append(str(n % 2))
        n //= 2
    
    # Reverse the list and join to get the binary string
    binary_digits.reverse()
    
    return ''.join(binary_digits)

# Example usage
if name == "main":
    decimal_number = 23
    binary_number = decimal_to_binary(decimal_number)
    print(f"The binary representation of {decimal_number} is {binary_number}.")
Explanation of the Function
- Input Validation: The function checks if the input is a non-negative integer. If not, it raises a ValueError. - Handle Zero: A special case is handled for the input 0, which directly returns "0" as its binary representation. - Conversion Logic: - The function uses a while loop to repeatedly divide the number by 2, storing the remainder (either 0 or 1) in a list as a string. - This process continues until the number becomes 0. - Final Step: The list of binary digits is reversed (since the first remainder corresponds to the least significant bit) and joined together to form the final binary string. This approach is efficient and illustrative of the mathematical foundation of binary conversion.