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 find(dec_num): #dec_num is the decimal number
    if(dec_num==0):
        # this will check if the number inuputed  has a remainder or not
        return
    else:
        find(int(dec_num/2))# this is for if the remainder is not 0, so it will divide by 2
        print(dec_num % 2, end="") #The % is to calulcate what the remainder is
        # We need to make sure to include the end="", because if we dont do this, the numbers will be printed in different lines, but we want them in one single line.

#now we need to call the function dec_num
find(10)
1010

EXTRA

Using the bin method

num = 23
# print(bin(num)) now if we just print this we will get something like this as an answer: 0b10111
#So if we want to remove the Ob, we want to add [2:]
print(bin(num)[2:])
10111

Bin with user input

num  = int(input("Please enter a number!"))
print(bin(num)[2:])
1100100

Converting text into binary

print(ord("A"))
# The ord function converts any character(letter) into an integer, this is case sensative
# we are going to build off of this

# Now if I want this in bianry form, I am going to use the format function
print(format(ord("A"), "b")) # "b" stands for binary 
# I am still a little unsure of why the string is needed, but I do know is that if we dont include it, it will not convert it into a binary number

text = "Hi I am going to convert this text into binary"
# So in the following code what I did was first use ord to convert each and every character in the string to an integer, then i used the format function to format it into a binary number
# the " " is the whitespace also the connector
# everything in the collection(whitespace) that we pass to the join() function will be joined together using the string
binary = " ".join(format(ord(c), "b") for c in text) # the for c will go through each and every character in the string and convert it into a binary
print(binary)
65
1000001
1001000 1101001 100000 1001001 100000 1100001 1101101 100000 1100111 1101111 1101001 1101110 1100111 100000 1110100 1101111 100000 1100011 1101111 1101110 1110110 1100101 1110010 1110100 100000 1110100 1101000 1101001 1110011 100000 1110100 1100101 1111000 1110100 100000 1101001 1101110 1110100 1101111 100000 1100010 1101001 1101110 1100001 1110010 1111001