-1

I am a beginner in python. I have written a program to convert decimal numbers to binary. It works. But Is there any other way to make it better? Refer to my code. Thanks :)

def decimal_to_binary_converter(dec):
    print(f"Decimal: {dec}")
    binary = ""
    # Using while loop dividing the decimal number by 2 and concatenating the reminder to the string variable "binary" .
    # % Operator gets the reminder from the division.
    while int(dec) > 0:
        binary += str(int(dec)%2)
        dec = int(dec) / 2
    x = int(len(binary))
    rev_binary = ""
    # using this while loop reversing the string "binary" and showing the Output.
    while x > 0:
        rev_binary += str(binary[x-1])
        x -= 1
    return print(f"Binary: {rev_binary}")


decimal_to_binary_converter(945)

Output:

Decimal: 945
Binary: 1110110001
Ak119
  • 1
  • 2
    Don't `return print(f"Binary: {rev_binary}")`. Your function is more useful if it returns something, if you do `return print(f"Binary: {rev_binary}")` then your function returns `None`, because `print` returns `None` – juanpa.arrivillaga Aug 16 '20 at 11:35
  • Don't use while loops to iterate over sequences in order like this, `while x > 0: ... x -= 1`, instead, use `reversed`. But the idiomatic way to reverse a sequence is simply `rev_binary = binary[::-1]` – juanpa.arrivillaga Aug 16 '20 at 11:37
  • @juanpa.arrivillaga Understood. Thanks. – Ak119 Aug 16 '20 at 11:39
  • 2
    Anyway, these sorts of questions aren't really on-topic for stack overflow, that is, asking for suggestions on how to imporve working code. There is a Stack Exchange site, [codereview.se] but this may not be appropriate for there either. – juanpa.arrivillaga Aug 16 '20 at 11:41
  • Okay thanks.. got it.. – Ak119 Aug 16 '20 at 12:11

1 Answers1

0

You can get it in one line

n = int(input())
binaryNo = bin(n).replace("0b","")
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219