Domanda

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))
È stato utile?

Soluzione 2

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)

Altri suggerimenti

You only set digc in one of the top if/else statement. If 32/denaryno<1 is True, you don't set digc at all.

Set digc at the top of the function (to 0 or whatever else you want it to be). This applies to all the digit variables, digd, dige, etc.

What you really should do, instead, is use a list of digits, and append either a 0 or a 1 to that list every time you divide the number by a factor.

You may want to take a look at the divmod() function; it returns both the quotient and the remainder. You could also do with some looping here to slash the number of if statements needed here:

number = int(input("Write a number from 1-64 "))
digits = []
factor = 64
while number:
    quotient, number = divmod(number, factor)
    digits.append(quotient)
    factor //= 2
print(''.join(map(str, digits)))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top