-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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Amit John
  • 1
  • 2

2 Answers2

0

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
  • 151
  • 1
  • 1
  • 10
  • Yep. Printed '0'. – Dean Jan 31 '20 at 07:52
  • No of course not, but that's not the question is it.... – Dean Jan 31 '20 at 07:56
  • @JustinEzequiel This is a question and answer site, not a discussion forum. Questions are **not there** to "help the OP"; they're there to *be questions* which are *useful for reference*. Solving problems for people who ask the questions is only an incidental incentive. Questions where there is more than one, unrelated problem are theoretically off topic anyway (they "need more focus"). – Karl Knechtel Sep 12 '22 at 11:02
-1

Changing decimal to binary is easy with numpy:

import numpy as np
np.binary_repr(4, width=None)
Dean
  • 151
  • 1
  • 1
  • 10