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.并且,把余数按相反的顺序写出来。我想用append,reverse,join函数,格式运算符(%)来做这个函数。此时,n为正数,半径为2到16。最后的结果是'基数10的61是基数16的3D'。
在你的代码中。x
只有当 2 <= radix <= 16
但无论如何,在底部你叫 print("%d in base 10 is %d in base %d" % (n1,x,radix1))
,它试图打印出 x
即使它没有被定义。要解决这个问题,可以将你的 print 语句移动到条件 if 2 <= radix <= 16
或定义 x
在你的else-statement中也是如此。
同时要注意你的缩进,并注意 replace_base(x)
不会改变x的值,除非你做了 x = replace_base(x)
.