Daniel Chettiar
Daniel Chettiar

Reputation: 143

Converting Decimal Number To Binary In Python 3

When I try to convert Decimal To Binary, The code executes with no error but the result is 'none'. Sometimes it just doesn't show anything. I feel there is some logical error can anyone help me correct what's wrong??

Code :

def bin_no():
    global rem
    
    n = int(input("Enter Number : ")) #Taking a Decimal Num
    
    while n >=1 :   #Initiating a Loop to Convert Decimal To Binary using the (Divide By 2 Method).
        rem = []
        n = n//2
        rem.append(n%2)
        
    if n !>=1:  #Going back to the loop if input is invalid.
        print("Please enter a Valid Number")
        bin_no()

    print("Binary Number : ", rem.reverse()) #Printing the result (the binary no. was stored in reverse order.)
bin_no()

Upvotes: 2

Views: 1675

Answers (2)

expl25
expl25

Reputation: 36

You don't need a recursive call here. It might produce some troubles.

def bin_no()
    n = 0
    while n < 1:
        n = int(input("Enter a Valid Number : "))
    rem = []
    while n > 0:
        rem.append(n % 2)
        n //= 2
    rem.reverse()
    print("Binary Number : ", rem)

Upvotes: 1

Aniket Tiratkar
Aniket Tiratkar

Reputation: 858

Here are a few problems with your code:

  1. rem = [] is inside the while loop, so in every loop iteration rem will become [] and in the end it will have only the last bit stored in it.

  2. The order of // and % operation is wrong, // will first truncate the data and % will always produce 0. You need to reverse the order of those operations.

  3. reverse is a list method that does in place reversal and returns None. That's why your code always prints None. So, you need to use rem.reverse() before the last print line and print rem normally.

After these changes, your code will look like this:

def bin_no():
    global rem
    
    n = int(input("Enter Number : ")) #Taking a Decimal Num
    
    rem = []
    while n >=1 :   #Initiating a Loop to Convert Decimal To Binary using the (Divide By 2 Method).
        rem.append(n%2)
        n = n//2
        
    if n >=1:  #Going back to the loop if input is invalid.
        print("Please enter a Valid Number")
        bin_no()
    rem.reverse()
    print("Binary Number : ", rem) #Printing the result (the binary no. was stored in reverse order.)

bin_no()

Upvotes: 3

Related Questions