-1

I am relatively new to python and I can't understand why does this throws an error.

ar=''
def decToBin(no):
    while(no>0):
        ar=ar+str(no%2)
        no=no//2
    print(ar[::-1])
decToBin(4)

code that works

def decToBin(no):
    ar=''
    while(no>0):
        ar=ar+str(no%2)
        no=no//2
    print(ar[::-1])
decToBin(4)

The scope of the "ar" variable is supposed to be global and should be accessible inside the function. Can anyone explain why the former isn't working?

Amit John
  • 1
  • 2

2 Answers2

0

Changing decimal to binary is easy with numpy:

import numpy as np
np.binary_repr(4, width=None)
Dean
  • 103
  • 1
  • 9
-1

The issue is this line:

ar=ar+str(no%2)

You are referencing it, before it has been assigned.

Try this instead:

ar = ''
def decToBin(no):
    while(no>0):
        #ar=ar+str(no%2)
        no=no//2
    print((ar+str(no%2))[::-1])
decToBin(4)
Dean
  • 103
  • 1
  • 9