Python 3.4.2 IDLE:定义' denaryInput'时出错

时间:2014-11-24 18:38:17

标签: python-3.x

我真的很喜欢编程和家庭作业,我们不得不使用用户输入的数字来对家庭作业进行二元转换。当我运行此代码时,我收到以下错误:

    if denaryInput < 0:
NameError: name 'denaryInput' is not defined

我不确定我做错了什么,并且非常感谢任何答案。

使用的代码:

"""We are asking the user for a number"""

def getNumber():
    denaryInput = int(input("Please enter a number between 0 and 255: "))

"""We are validating the number"""

def validateNumber():
    if denaryInput < 0:
        print("Error: Number is too small, try again!" + " \n")
        return False
    elif denaryInput > 255:
        print("Error: Number is too big, please try again!" + " \n")
        return False
    else:
        return True

def binaryNumber():
    result = []
    for number in range(8):
        bit = denaryInput % 2
        result.append(bit)
        denaryInput = denaryInput // 2
    result.reverse()
    str1 = "".join(str(x)for x in result)
    print (str1 + " \n")    

"""Now telling the computer to run the code above and in what order of operations"""

def mainProgram():
    answer = getNumber()
    validNum = validateNumber()
    Binary = binaryNumber()
    print("The binary equlivent for that number is " + Binary + " \n")

mainProgram()

1 个答案:

答案 0 :(得分:0)

您需要从getnumber函数传递denaryInput作为调用的一部分。 validatenumber函数需要传递给它的值才能实际验证。这些在每个函数中应该是不同的名称。 E.g:

def validateNumber(numIn):
    if numIn < 0

此外,您应该验证来自getnumber函数的数字

denaryInput = int(input("Please enter a number between 0 and 255: "))
if validateNumber(denaryInput): #returns true if number valid
    Return denaryInput

最后,二进制是一个关键字,不应出现在你的主函数中。