我看不出我会在哪里出错 - 其他答案似乎指出这是在函数中不当使用全局变量,但我很确定我没有以这种方式犯罪。
当我运行此代码时,它成功地提示我输入所有数据行,但是一旦它尝试运行第一个函数,就会发生错误......
有人可以向我指出我做错了什么吗?
我收到的错误消息是:
UnboundLocalError: local variable 'monthlyValue' referenced before assignment on line 17 in main.py
我的整个程序是这样的:
def calcMonthlyYearlyValues(weeklyVsYearlyVsQuarterly,initialValue):
if(weeklyVsYearlyVsQuarterly.upper() == "W"):
yearlyValue = initialValue * 52
monthlyValue = round(float(yearlyValue / 12),2)
elif (weeklyVsYearlyVsQuarterly.upper() == "Y"):
yearlyValue = initialValue
monthlyValue = round(float(yearlyValue / 12),2)
elif (weeklyVsYearlyVsQuarterly.upper() == "Q"):
yearlyValue = initialValue * 4
monthlyValue = round(float(yearlyValue / 12),2)
return monthlyValue, yearlyValue
def inputRowValues(rowDescription):
print rowDescription
rowName = input("Enter Item Name: ")
rowPeriodType = input("W/ M/ Q/ Y for Weekly/ Monthly/ Quarterly or Yearly:")
rowValue = float(input("Enter Amount: "))
print ""
return rowName, rowPeriodType, rowValue
row1Name, row1PeriodType, row1Value = inputRowValues("Row 1")
row2Name, row2PeriodType, row2Value = inputRowValues("Row 2")
row3Name, row3PeriodType, row3Value = inputRowValues("Row 3")
row4Name, row4PeriodType, row4Value = inputRowValues("Row 4")
row5Name, row5PeriodType, row5Value = inputRowValues("Row 5")
row1Monthly, row1Yearly = calcMonthlyYearlyValues(row1PeriodType,row1Value)
row2Monthly, row2Yearly = calcMonthlyYearlyValues(row2PeriodType,row2Value)
row3Monthly, row3Yearly = calcMonthlyYearlyValues(row3PeriodType,row3Value)
row4Monthly, row4Yearly = calcMonthlyYearlyValues(row4PeriodType,row4Value)
row5Monthly, row5Yearly = calcMonthlyYearlyValues(row5PeriodType,row5Value)
column1 = "Item"
column2 = "Month"
column3 = "Year"
print "Monthly Budget"
print "========================================"
print "{0:<15} {1:^10} {2:^10}".format(column1, column2, column3)
print "========================================"
print "{0:<15} ${1:>10,.2f} ${2:>10,.2f}".format(row1Name, row1Monthly, row1Yearly)
print "{0:<15} ${1:>10,.2f} ${2:>10,.2f}".format(row2Name, row2Monthly, row2Yearly)
print "{0:<15} ${1:>10,.2f} ${2:>10,.2f}".format(row3Name, row3Monthly, row3Yearly)
print "{0:<15} ${1:>10,.2f} ${2:>10,.2f}".format(row4Name, row4Monthly, row4Yearly)
print "{0:<15} ${1:>10,.2f} ${2:>10,.2f}".format(row5Name, row5Monthly, row5Yearly)
感谢尼克的评论 - 我意识到我错过了一个 elif,如下所示:
def calcMonthlyYearlyValues(weeklyVsYearlyVsQuarterly,initialValue):
if(weeklyVsYearlyVsQuarterly.upper() == "W"):
yearlyValue = initialValue * 52
monthlyValue = round(float(yearlyValue / 12),2)
elif (weeklyVsYearlyVsQuarterly.upper() == "Y"):
yearlyValue = initialValue
monthlyValue = round(float(yearlyValue / 12),2)
elif (weeklyVsYearlyVsQuarterly.upper() == "M"):
yearlyValue = initialValue * 12
monthlyValue = initialValue
elif (weeklyVsYearlyVsQuarterly.upper() == "Q"):
yearlyValue = initialValue * 4
monthlyValue = round(float(yearlyValue / 12),2)
return monthlyValue, yearlyValue