Home » Python » Python programs

Python | Convert the decimal number to binary without using library function

Decimal to binary in Python: Here, we are going to learn how to convert the given decimal number to the binary number without using any library function in Python?
Submitted by IncludeHelp, on August 09, 2019

Given a decimal number and we have to convert it into binary without using library function.

Example:

    Input: 
    10

    Output: 
    1010

Python code to convert decimal to binary

# Python code to convert decimal to binary

# function definition
# it accepts a decimal value 
# and prints the binary value
def decToBin(dec_value):
    # logic to convert decimal to binary 
    # using recursion
    bin_value =''
    if dec_value > 1:
        decToBin(dec_value//2)
    print(dec_value % 2,end = '')

# main code
if __name__ == '__main__':
    # taking input as decimal 
    # and, printing its binary 
    decimal = int(input("Input a decimal number: "))
    print("Binary of the decimal ", decimal, "is: ", end ='')
    decToBin(decimal)

Output

First run:
Input a decimal number: 10
Binary of the decimal  10 is: 1010

Second run:
Input a decimal number: 963
Binary of the decimal  963 is: 1111000011     





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.