Homework/Hacks

our homework we have decided for a decimal number to binary converter. You must use conditional statements within your code and have a input box for where the decimal number will go. This will give you a 2.7 out of 3 and you may add anything else to the code to get above a 2.7.

Below is an example of decimal number to binary converter which you can use as a starting template.

def DecimalToBinary(num):
    strs = ""
    while num:
        # if (num & 1) = 1
        if (num & 1):
            strs += "1"
        # if (num & 1) = 0
        else:
            strs += "0"
        # right shift by 1
        num >>= 1
    return strs
 
# function to reverse the string
def reverse(strs):
    print(strs[::-1])
 
# Driver Code
num = 67
print("Binary of num 67 is:", end=" ")
reverse(DecimalToBinary(num))
Binary of num 67 is: 1000011

After understanding the base model, I tried to make my own...

def convert(n):
# got help from Jiya to start it off 
    if n == 0:
        print("0")
    elif n == 1:
        print("1")
    else:
        binary = "" # define a variable for string "" to store binary numbers
        # divide (n) by 2 until it becomes 0 with the modulo operator %
        # The remainder is stored in the variable that I just defined
        while int(n) > 0:
            binary += str(int(n%2)) # get the remainder, and keep appending to the string to add it to the end
            n = n / 2 # change the number to its quotient, then repeat the process
        print(binary[::-1]) # now we can print the binary string, but it needs to be reversed with ::
        
n = int(input('enter a number and watch some binary magic happen'))
convert(n) # the function should work for any positive whole number now
110010000