对于python来说相对较新,似乎无法解决为什么程序不会在调用该函数之前运行的麻烦。我似乎无法识别名称错误。请帮助
decimal = int(input("Enter decimal number to convert to base: "))
base = int(input("Enter base for the conversion: "))
print(" ____")
print(str(base)+"|"+str(decimal))
conversion = numSyst(decimal,base)
print("Base "+str(base)+" value of "+str(decimal)+" = "+conversion)
def hex(remainder):
hexN = ""
if (remainder >=10 and remainder <=15):
if remainder == 10:
hexN = "A"
if remainder == 11:
hexN = "B"
if remainder == 12:
hexN = "C"
if remainder == 13:
hexN = "D"
if remainder == 14:
hexN = "E"
if remainder == 15:
hexN = "F"
elif int(remainder) <= 9:
hexN = str(remainder)
return hexN
def numSyst(decimal,base):
num = ""
remainder =-1
if decimal == 0:
num = "0";
else:
while decimal > 0:
remainder = int(decimal%base)
decimal = int(decimal//base)
if base == 16:
convert = int(remainder)
num = num + hex(remainder)
else:
num = num + str(remainder)
return num
答案 0 :(得分:1)
确保先定义hex
,然后再定义numSyst
,然后再定义代码来调用numSyst
。在Python中,如果要使用类似此处的独立脚本,则应先定义要使用的函数。
def hex(remainder):
hexN = ""
if (remainder >=10 and remainder <=15):
if remainder == 10:
hexN = "A"
if remainder == 11:
hexN = "B"
if remainder == 12:
hexN = "C"
if remainder == 13:
hexN = "D"
if remainder == 14:
hexN = "E"
if remainder == 15:
hexN = "F"
elif int(remainder) <= 9:
hexN = str(remainder)
return hexN
def numSyst(decimal,base):
num = ""
remainder =-1
if decimal == 0:
num = "0"
else:
while decimal > 0:
remainder = int(decimal%base)
decimal = int(decimal//base)
if base == 16:
convert = int(remainder)
num = num + hex(remainder)
else:
num = num + str(remainder)
return num
decimal = int(input("Enter decimal number to convert to base: "))
base = int(input("Enter base for the conversion: "))
print(" ____")
print(str(base)+"|"+str(decimal))
conversion = numSyst(decimal,base)
print("Base "+str(base)+" value of "+str(decimal)+" = "+conversion)
#Enter decimal number to convert to base: 15
#Enter base for the conversion: 2
#____
#2|15
#Base 2 value of 15 = 1111