Given a decimal number as input, the task is to write a Python program to convert the given decimal number into equivalent binary number.
Examples :
Input : 7 Output :111 Input :10 Output :1010
Method #1: Recursive solution
DecimalToBinary(num):
if num > 1:
DecimalToBinary(num // 2)
print num % 2

Below is the implementation of above recursive solution:
# Function to convert decimal number # to binary using recursion def DecimalToBinary(num): if num > 1: DecimalToBinary(num // 2) print(num % 2, end = '') # Driver Code if __name__ == '__main__': # decimal value dec_val = 24 # Calling function DecimalToBinary(dec_val) |
11000
Method #2: Decimal to binary using in-built function
# Python program to convert decimal to binary # Function to convert Decimal number # to Binary number def decimalToBinary(n): return bin(n).replace("0b", "") # Driver code if __name__ == '__main__': print(decimalToBinary(8)) print(decimalToBinary(18)) print(decimalToBinary(7)) |
1000 10010 111
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
Recommended Posts:
- Program to Convert BCD number into Decimal number
- Python program to convert float decimal to Octal number
- Program to convert Hexa-Decimal Number to its equivalent BCD
- Program to convert a BCD to Hexa-Decimal Number
- Python program to convert hex string to decimal
- Python program to convert any base to decimal by using int() method
- Convert a given Decimal number to its BCD representation
- Quickly convert Decimal to other bases in Python
- Convert Decimal to String in Python
- Program for Binary To Decimal Conversion
- Program for Decimal to Binary Conversion
- Recursive Program for Binary to Decimal
- Convert from any base to decimal and vice versa
- Convert all substrings of length 'k' from base 'b' to decimal
- Decimal to binary number using recursion
- Program to Convert Octal Number to Binary Number
- Binary to decimal and vice-versa in python
- Python | Decimal to binary list conversion
- Python Program to Convert any Positive Real Number to Binary string
- Decimal to binary conversion without using arithmetic operators
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet

