English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonction en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program converts decimal to binary

Python complete examples

In this program, you will learn to use recursive functions to convert decimal numbers to binary numbers.

To understand this example, you should understand the followingPython programmingTopic:

Decimal numbers are obtained by dividing the numbers successively by2and print the remainders in reverse order to convert to binary numbers.

Source code

# Function to print binary numbers using recursion
def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')
# Decimal number
dec = 34
convertToBinary(dec)
print()

Output results

110100

You can change the variable dec in the above program and run it to test other values.

This program is only for integers. It is not suitable for fractional values25.5,45.64of real numbers. We encourage you to create a Python program to convert all decimal numbers of real numbers to binary.

Python complete examples