不明白为什么:NameError:名称“ numSyst”未定义

时间:2019-04-16 13:42:16

标签: python-3.x

对于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)

numSyst函数中使用的函数

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

用于进行转换的函数-包含NameError

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      

1 个答案:

答案 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