Binary to denary and vice versa


#1



my code doesn't actually print anything out. i tried to call on the functions but they didn't work.


def denaryToBinary(denaryNo):#the name of the function
    if denaryNo <= 255:#to make sure you can turn it into an bite
        x = []#the empty binary list
        y = 128#for the first 1 or 0 in binary

        while y >= 1:#the while...else loop to turn my number into binary
            if denaryNo - y > 0:#to make the number 1
                denaryNo -= y#to take away the 2^y number
                x.append(1)#to put a 1 there
                y = y / 2#to get to the next number

            elif denaryNo - y == 0:
                x.append(1)#in case the binary number is equal to the 2^y number

            else:
                x.append(0)#to put a 0 there

        else:
            return x#when the loop finishes

def binaryToDenary(binaryNo):
    binaryNo = [int(x) for x in str(binaryNo)]
    x = len(binaryNo)
    y = 0
    if x >= 8:
        return "this isn't a bite"
    elif x <= 7:
        while x > 0:
            if binaryNo[x-1] == 1:
                y += 2**(x+2)
                x -= 1
            elif binaryNo[x-1] == 0:
                x -= 1
            else:
                return "wait...this isn't a binary number!"
        else:
            return y

carryOn = True

while carryOn == True:
    binaryOrDenary = input("is the number you are going to input a binary or a denary number? B or D")
    theInput = int(input("the number please!"))

    if binaryOrDenary.lower() == "b":
        print(binaryToDenary(theInput))

    elif binaryOrDenary.lower() == "d":
        print(denaryToBinary(theInput))

    else:
        print("that wasn't an option")

    carryOn = input("do you want to carry on? y/n")

    if carryOn.lower() == "y":
        carryOn = True

    elif carryOn.lower() == "n":
        carryOn = False

else:
    print("goodbye")


#2

Your code prompts for input, so it does print something. Perhaps you mean something else? Or if you meant that it prints nothing, then the problem is in how you are invoking your program

If the problem isn't with printing, but with terminating, then I suggest adding prints in your code that say what it's currently doing, thus allowing you to see what it does differently from what you wanted


#3

i tried that when i was making it. when i was making it i called on the function and it worked perfectly but when i finished creating the selection section it didn't work.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.