Basic Programs

If Else Programs

While loop Programs

For loop Programs

List Programs


Python Program to Convert Decimal to Binary using While Loop


In this example shows, how to convert a decimal number to binary number using while loop.

Steps
  1. The function binary converts a decimal (base 10) integer to its binary (base 2) representation.This line defines a function named binary that takes one parameter, decimal.
  2. Inside the loop, the expression decimal % 2 computes the remainder when decimal is divided by 2. This remainder is either 0 or 1, which are the possible digits in binary.
  3. After the loop completes (when decimal becomes 0), the function returns the binary string, which now contains the binary representation of the original decimal number.
Example:

Example.py
def binary(decimal): 
  binary = "" 
  while decimal > 0: 
    binary = str(decimal % 2) + binary 
    decimal = decimal // 2 
  return binary 

dec = int(input("Enter the Decimal value :"))
print(binary(dec)) 

Output

Enter the Decimal value :12
1100

Prev Next