In this tutorial, we will learn how to convert a decimal number to binary using recursion in Python. We will cover the basic concept of binary numbers and implement a recursive function to perform the 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.
The syntax to convert a decimal number to binary using recursion in Python is:
def decimal_to_binary(n):
if n == 0:
return '0'
elif n == 1:
return '1'
else:
return decimal_to_binary(n // 2) + str(n % 2)
We can create a recursive function to convert a given decimal number to binary by continuously dividing the number by 2 and keeping track of the remainders.
For example,
decimal_to_binary
that takes one parameter n
.n
is 0. If true, return '0'.n
is 1. If true, return '1'.n // 2
and append the remainder of n % 2
to the result.def decimal_to_binary(n):
if n == 0:
return '0'
elif n == 1:
return '1'
else:
return decimal_to_binary(n // 2) + str(n % 2)
# Convert 10 to binary
result = decimal_to_binary(10)
# Print the result
print('Binary representation of 10 is', result)
Binary representation of 10 is 1010