变量未在函数内初始化

时间:2018-04-01 23:08:35

标签: python

我被赋予了在Python中编写罗马数字转换器的任务。我应该使用三个功能。这是我到目前为止所做的:

    ##Get a roman numeral from the user
    # @param userInput the roman numeral given 
    # @return The value to calculateValue
    # pg 252
    def getInput() :
        userInput = input("Please enter a Roman numeral: ")
        storedInput = userInput
        if userInput.islower() :
            userAlphaInput = userInput.upper()
        else :
            userAlphaInput = userInput
        return userAlphaInput, storedInput

    ##Converts the Roman numeral to a number
    # @param Converts Roman numeral
    # @return the number to displayOutput
    #
    def calculateValue() :
        M = 1000
        D = 500
        C = 100
        L = 50
        X = 10
        V = 5
        I = 1
        while userInput == True :
            if userInput[0] >= userInput[1] or len(userInput) == 1 :
                convertedNumber += (userInput[0])
                del userInput[0]
           else :
                convertedNumber += (userInput[1]) - (userInput[0])
                del userInput[0], userInput[1]
        return convertedNumber

    ##Displays the result
    # @param convertedNumber the converted number
    # @return the stored and converted number
    #
    def displayOutput() :
        print( storedInput, "is ", convertedNumber)

    getInput()
    calculateValue()
    displayOutput()

但是我得到了第45行没有定义userInput的错误。我认为该变量将在第一个函数中初始化。我不正确理解吗?任何和所有的帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

这是一个范围问题。定义userInput时,它仅在函数getInput()内定义。

要解决您的问题,请在userInput之外定义storedInputgetInput()

有关详情,请参阅here

答案 1 :(得分:0)

##Get a roman numeral from the user
# @param userInput the roman numeral given
# @return The value to calculateValue
# pg 252
def getInput() :
    userInput = input("Please enter a Roman numeral: ")
    storedInput = userInput
    if userInput.islower() :
        userAlphaInput = userInput.upper()
    else :
        userAlphaInput = userInput
    return userAlphaInput, storedInput

##Converts the Roman numeral to a number
# @param Converts Roman numeral
# @return the number to displayOutput
#
def calculateValue():
    userInput = getInput()
    convertedNumber = 0
    M = 1000
    D = 500
    C = 100
    L = 50
    X = 10
    V = 5
    I = 1
    while userInput == True :
        if userInput[0] >= userInput[1] or len(userInput) == 1 :
            convertedNumber += (userInput[0])
            del userInput[0]
    else :
        convertedNumber += (userInput[1]) - (userInput[0])
        del userInput[0], userInput[1]
    return convertedNumber

##Displays the result
calculateValue()
相关问题