Python Tutorials

Python Programs

Python Convert Decimal to Binary


Python Convert Decimal to Binary

In this tutorial, we will learn how to convert a decimal number to binary in Python. We will cover the basic concept of binary numbers and implement a function to perform the conversion.


What is Binary Conversion

Binary conversion is the process of converting a decimal (base-10) number to a binary (base-2) number. In binary, numbers are represented using only 0s and 1s.


Syntax

The syntax to convert a decimal number to binary in Python is:

def decimal_to_binary(n):
    return bin(n).replace('0b', '')


Converting a decimal number to binary

We can create a function to convert a given decimal number to binary using Python's built-in functions.

For example,

  1. Define a function named decimal_to_binary that takes one parameter n.
  2. Use the built-in bin function to convert the decimal number to binary.
  3. Remove the '0b' prefix from the binary representation using the replace method.
  4. Return the binary representation as a string.
  5. Call the function with a sample number and print the result.

Python Program

def decimal_to_binary(n):
    return bin(n).replace('0b', '')

# Convert 10 to binary
result = decimal_to_binary(10)

# Print the result
print('Binary representation of 10 is', result)

Output

Binary representation of 10 is 1010