Converting Decimal to Binary in python

geekhandsm

Thread Starter
Joined
Oct 21, 2021
Messages
1
I was trying to convert Decimal to Binary, there is no error in the code but while executing I am getting blank, not showing anything. Could someone help me figure out where is the mistake?


Code:
def decimalToBinary(ip_val):
    if ip_val= 1:
    # recursive function call
        decimalToBinary(ip_val // 2)
    
    # printing remainder from each function call
    print(ip_val % 2, end = '')
 
# Driver Code
if __name__ == '__main__':
    # decimal value
    ip_val = 24
    
    # Calling special function
    decimalToBinary(ip_val)
I have read this article to understand the concept and tried this.
 

Xsage

Dave
Joined
Jan 8, 2016
Messages
345
two things I notice:
1) Line 2, the if statement needs a ">=" instead of a "=".

2) I don't know much python, but I believe the issue is related to the shell only being allowed to display a complete line.
By including end = '', you are telling the shell that the line isn't complete and ready to display because you have extra stuff you want to add to it. If you where to add another print right after that that has a carriage return or a line feed, it will display the intended output.

The reason they include this is because of the recursive function call, this allows them to use the same method to append a all of the numbers ready to be output. Then by calling a new line, you will get the results.

e.g:
Python:
# Recursive Function to convert decimal to binary
def decimalToBinary(ip_val):
    if ip_val >= 1:
    # recursive function call
        decimalToBinary(ip_val // 2)
  
    # printing remainder from each function call
    print(ip_val % 2, end = '')

# Driver Code
if __name__ == '__main__':
    # decimal value
    ip_val = 24
    # Calling special function
    decimalToBinary(ip_val)
    print("\n")
    ip_val = 24
    # Calling special function
    decimalToBinary(ip_val)
    ip_val = 25
    # Calling special function
    decimalToBinary(ip_val)
    ip_val = 26
    # Calling special function
    decimalToBinary(ip_val)
    ip_val = 27
    # Calling special function
    decimalToBinary(ip_val)
    print("\n")
output:
Code:
011000

011000011001011010011011

>
 
Last edited:

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Staff online

Top