-1
def replace_base(x):
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    x = x.replace('16', 'G')
    return x

def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    if n>0:
        if 2<=radix<=16:
            while int(n/radix) == 0:
                converted_number.append(n % radix)
                converted_number.reverse()
                x = ''.join(str(i) for i in converted_number)
                replace_base(x)
            else:
                converted_number.append(n % radix)
        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")

    print("%d in base 10 is %d in base %d" % (n1,x,radix1))

deci_to_any_list()

Input & error,

Enter a number: 61
Enter a radix: 16
Traceback (most recent call last):
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 33, in <module>
    deci_to_any_list()
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 31, in deci_to_any_list
    print("%d in base 10 is %d in base %d" % (n1,x,radix1))
UnboundLocalError: local variable 'x' referenced before assignment

Process finished with exit code 1

I want to create a decimal transformation function. I posted a question earlier, but you asked me to give you more details, so I'm leaving a question again. I don't know how to fix the error, and I don't know how to make this function. It can make to divide the quotient by the radix base number until the quotient is 0. And, write remainders in reverse order. I want to make this function using the append, reverse,join function,formatting operator(%). At this time, n shall be positive number and radix shall be 2 to 16. The last result is '61 in base 10 is 3D in base 16'.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Dududu
  • 3
  • 1
  • All you need to fix your error is: declare `x = ''` before `if n>0:...`. – CypherX May 30 '20 at 07:39
  • 1
    What's your question? Please [edit] to clarify. I'm inferring you want to know how to fix it, but please be specific and explicit. BTW welcome to SO! Please read the [tour] and [ask]. – wjandrea May 30 '20 at 17:57
  • This might be a duplicate of [this question](https://stackoverflow.com/q/15367760/4518341) – wjandrea May 30 '20 at 18:03

1 Answers1

0

In your code, x only gets defined if 2 <= radix <= 16, yet regardless, at the bottom you call print("%d in base 10 is %d in base %d" % (n1,x,radix1)), which attempts to print out x even if it wasn't defined. To fix this, either move your print statement inside the condition if 2 <= radix <= 16, or define x in your else-statement as well.

Also be careful about your indentation, and note that replace_base(x) does not change the value of x unless you do x = replace_base(x).

bug_spray
  • 1,445
  • 1
  • 9
  • 23