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()
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
我想创建一个十进制转换函数。我之前发布了一个问题,但您要求我提供更多详细信息,所以我再提一个问题。我不知道如何解决该错误,我也不知道如何实现此功能。可以将商除以基数基数,直到商为0。然后,以相反的顺序写余数。我想使用附加,反向,联接功能,格式化运算符(%)来实现此功能。此时,n为正数,基数为2到16。最后的结果是'以10为底的61是以16为底的3D'。
根据我的说法,您的代码中有许多更正:
x = ""
之前声明变量if n>0:...
while
循环converted_number
列表中添加商replace_base(x)
的结果分配给x
这里是修改后的功能:
def deci_to_any_list():
n1 = input("Enter a number: ")
n = int(n1)
radix1 = input("Enter a radix: ")
radix = int(radix1)
converted_number = []
x=""
if n>0:
if 2<=radix<=16:
if int(n/radix) != 0:
converted_number.append(n % radix)
converted_number.append(int(n / radix))
converted_number.reverse()
x = ''.join(str(i) for i in converted_number)
x = replace_base(x)
else:
converted_number.append(n % radix)
else:
print("Wrong input!!")
else:
print("Wrong input!!")
print("{} in base 10 is {} in base {}".format(n1,x,radix1))