Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to convert decimal to binary - Python Program

Example 1 :

def decimal_to_binary(n): """Convert decimal to binary recursively.""" if n == 0: return "0" if n == 1: return "1" return decimal_to_binary(n // 2) + str(n % 2) print(decimal_to_binary(13))

Output

 
OUTPUT  :
1101

Example 2 : Advanced Program

def decimal_to_binary_recursive(n): """ Recursively converts a non-negative decimal integer to its binary representation. Args: n (int): The decimal integer to convert. Returns: str: The binary representation of the decimal integer. """ if n == 0: return "0" # Base case: 0 in decimal is "0" in binary elif n == 1: return "1" # Base case: 1 in decimal is "1" in binary else: # Recursive step: divide by 2, get remainder, and concatenate return decimal_to_binary_recursive(n // 2) + str(n % 2) # Example Usage: decimal_number_1 = 25 binary_representation_1 = decimal_to_binary_recursive(decimal_number_1) print(f"The decimal number {decimal_number_1} in binary is: {binary_representation_1}") decimal_number_2 = 10 binary_representation_2 = decimal_to_binary_recursive(decimal_number_2) print(f"The decimal number {decimal_number_2} in binary is: {binary_representation_2}") decimal_number_3 = 0 binary_representation_3 = decimal_to_binary_recursive(decimal_number_3) print(f"The decimal number {decimal_number_3} in binary is: {binary_representation_3}")

Output

 
OUTPUT  :
The decimal number 25 in binary is: 11001
The decimal number 10 in binary is: 1010
The decimal number 0 in binary is: 0