Search code examples
pythondefined

Why does this Python 3.3 code not work? digc not defined


It prints diga and digb but doesnt work with c! Any help? It's supposed to be a Denary to Binary converter but only 1-64, once i've cracked the code will increase this! Thanks so much

denaryno=int(input("Write a number from 1-64 "))
if 64%denaryno > 0:
    diga=0
    remaindera=(64%denaryno)
    if 32/denaryno<1:
        digb=1
        remainderb=(denaryno%32)
    else:
        digb =0
        if 16/remainderb<1:
            digc=1
            remainderc=(denaryno%16)
        else:
            digc=0
            if 8/remainderc<1:
                digd=1
                remainderd=(denaryno%8)
            else:
                digd=0
                if 4/remainderd<1:
                    dige=1
                    remaindere=(denary%4)
                else:
                    dige=0
                    if 2/remaindere<1:
                        digf=1
                        remainderf=(denary%2)
                    else:
                        digf=0
                        if 1/remainderf<1:
                            digg=1
                            remainderg=(denary%1)
                        else:
                            digg=0
print (str(diga)+str(digb))

Solution

  • Wow that was a lot of work, you don't have to do all that.

    def bin_convert(x, count=8):
        return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
    

    here are the functions comprising this one from easy->important

    str() returns a string

    range() is a way to get a list from 1 number to another. Written like this range(count-1, -1, -1) counts backwards.

    "".join() is a way to take an iterable and put the pieces together.

    map() is a way to take a function and apply it to an iterable.

    lambda is a way to write a function in 1 line. I was being lazy and could have written another def func_name(y) and it would have worked just as well.

    >> is a way to shift bits. (which I believe understanding this one is the key component to understanding your problem)