In this article, we will discuss how to convert decimal numbers to binary numbers using recursion in Python. We will also explore the significance of this concept in computer science, its applications, and its implementation in Python.
Understanding Decimal and Binary System
Before we start writing the code to convert decimal to binary using recursion, it is essential to understand the decimal and binary system. The decimal system is a base-10 number system that uses ten digits, 0-9, to represent any number. In contrast, the binary system is a base-2 number system that uses only two digits, 0 and 1, to represent any number.
Recursive Function to Convert Decimal to Binary
Now that we have understood the basics of the decimal and binary system let’s write the code to convert decimal to binary using recursion in Python. Here is the code that we will be using:
def decimalToBinary(n): if n > 1: decimalToBinary(n//2) print(n % 2,end = '') #Driver code if __name__ == '__main__': decimalToBinary(10)
Let’s understand how this code works.
decimalToBinary() takes a decimal number as input and recursively calls itself with the quotient of the division of the number by 2. The function keeps on calling itself until the quotient becomes less than 2. Finally, the function prints the remainder of the division of the number by 2.
The driver code calls the
decimalToBinary() function with the decimal number 10. The function converts the decimal number to binary and prints the output as
Testing the Code
Now that we have written the code to convert decimal to binary using recursion, let’s test the code with some other decimal numbers. Here is the code that we will be using to test the function:
def test_decimalToBinary(): assert decimalToBinary(2) == 10 assert decimalToBinary(10) == 1010 assert decimalToBinary(15) == 1111 if __name__ == '__main__': test_decimalToBinary() print("All test cases pass")
test_decimalToBinary() function contains three assert statements that test the
decimalToBinary() function’s output with different decimal numbers. If all the test cases pass, the code will print “All test cases pass” as the output.
Converting decimal to binary using recursion in Python is a simple task, and it can be achieved with just a few lines of code. We hope that our article has provided you with a comprehensive guide that can help you understand how to convert decimal to binary using recursion in Python.
Thanks for reading. Happy coding!