使用定义和接收值时出错

时间:2014-11-16 05:12:05

标签: python

你好,这是我的代码:

def main():
    #Define Variables
    HomesSold = [0]
    Amount = 0
    HomePrice = [0]
    Amount = GetAmount(Amount)
    HomesSold = AmountHomesSold(Amount)
    #print(HomesSold)


def GetAmount (Amount):
    global amount
    ConvertAmount = float()
    ErrorFlag = False
    Amount = input("Enter the amount of homes sold this year:")
    while not Amount.isdigit():
        Amount = input("Please try again, make sure you are entering a positive number (No commas needed): ")

    print("The amount of houses sold were: ",Amount)
    ConvertAmount = float(Amount)
    return ConvertAmount

def AmountHomesSold(HomePrice):
    HomePrice = 0
    index = 0
    while (index < Amount):
        HomePrice = GetHomePrice()
        HomesSold[index] = HomePrice
        index = index + 1
        print(HomePrice)

    return HomePrice

def GetHomePrice():
    HomePrice = input("How much did the homes sell for?")
    while not HomePrice.isdigit():
        HomePrice = input("Please try again, make sure you are entering a positive number (No commas needed): ")


    return HomePrice

main()

所以当我尝试为index&lt;设置我的while语句时金额,我一直收到一个错误,说明在我的代码中较早时未定义金额。有没有办法可以收到这个号码?

1 个答案:

答案 0 :(得分:0)

您必须申报&#34;金额&#34;作为&#34; AmountHomesSold()&#34;中的全局变量为了使用它的价值。否则,它将查找名为&#34; Amount&#34;的局部变量。 in&#34; AmountHomesSold()&#34; (并且该功能中没有定义一个)。

注意:我添加了&#34;全球金额&#34;在第二行允许该功能使用&#34; Amount&#34;作为全球变量。

def AmountHomesSold():
    global Amount
    HomePrice = 0
    index = 0
    while (index < Amount):
        HomePrice = GetHomePrice()
        HomesSold[index] = HomePrice
        index = index + 1
        print(HomePrice)

        return HomePrice

有关详细信息,请参阅Use of "global" keyword in Python