A binary converter

I’m a hobbyist programmer and I program mainly in python, but am learning Ruby,which is similar to python. In this post I’m going to show you a simple python program:

#program loop
while True:
    userinput = int(input('Which decimal integer would you like converted to binary?'))
    if userinput == 0:
        binary = ''
        while int(userinput) > 0:
            digit = str(userinput % 2)
            userinput = userinput / 2
            binary = digit + binary

Can you guess what this does? If you guessed that it converts decimal numbers to binary numbers, you’re correct. I’ll be explaining how it does that now. If you want to try this program yourself you have to use python 3. I will be breaking the code up into little pieces and explain what they do.


First lets start with the part marked as input. All it really does is ask you the question: “Which decimal integer would you like converted to binary?” and sets the variable “userinput” to the response of the user to that question.


1. It checks if the value “userinput” is equal to zero.    if userinput == 0:

1a.The program prints 0.  print(‘0’)

1b.The program skips to the next loop.    continue

2. It does the following steps if “userinput” wasn’t equal to zero.    else:

2a. It prepares following steps by creating a variable called “binary” and setting it’s value to a blank string.    binary = ‘ ‘

2b. It will loop these statements as long as “userinput” is positive.                             while int(userinput) > 0:

~this statement sets the variable “digit” to the mod (the remainder) but as a string.    digit = str(userinput % 2)

~this step divides “userinput” by 2.    userinput = userinput / 2

~the last step of the loop puts the variable “digit” in front of binary.                            binary = digit + binary


The output step doesn’t do much. It just prints the “binary” value.


variable: an interchangeable value

algorithm: a sequence of commands

function: a kind of command


#something –> This is a comment. It will not be read by python. You can obviously put in anything for “something”

while a == b: –>This is a loop it will loop through the algorithm that come after it as long as the statement after the while is true.

examplevariable = 1 –>This command sets a value to a variable.

This entry was posted in programming, Python and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *