BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Program to Convert Decimal to Binary

By Chaitanya Singh | Filed Under: Python Examples

In this post, we will see programs to convert decimal number to an equivalent binary number. We will see two Python programs, first program does the conversion using a user defined function and in the second program we are using a in-built function bin() for the decimal to binary conversion.

1. Decimal to Binary conversion using recursive function

In this program we have defined a function decimalToBinary() for the conversion. This function takes the decimal number as an input parameter and converts it into an equivalent binary number.

def decimalToBinary(num):
    """This function converts decimal number
    to binary and prints it"""
    if num > 1:
        decimalToBinary(num // 2)
    print(num % 2, end='')


# decimal number
number = int(input("Enter any decimal number: "))

decimalToBinary(number)

Output:
python program decimal to binary conversion

2. Python program to convert decimal number to binary using bin() function

In this program, we are using a in-built function bin() to convert the decimal number to binary.

# decimal number
number = int(input("Enter any decimal number: "))

# print equivalent binary number
print("Equivalent Binary Number: ", bin(number))

Output:

Enter any decimal number: 42
Equivalent Binary Number:  0b101010

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap