赋值前引用的局部变量。函数适用于一个值而不是另一个值?

时间:2016-10-06 01:45:53

标签: python

这是我的代码

def sallaryOnDay(numDays):

  sallaryInCents = 2**(numDays-1)

  return sallaryInCents

def moneyAccumulator(numDays):
  income = 0
  counter = 1
  savedUp = 0
  while counter <= numDays:
    income += 2**(counter-1)
    counter = counter + 1

  return income

def convertToDollars(moneyInCents):
  if moneyInCents >= 100:
    moneyInDollars = moneyInCents/100

  return moneyInDollars

def main():
  userDays = int(input("Please enter the number of days: "))
  print("Day",  '\t', "Sallary",)
  print("---",   '\t',"-------")
  counter = 1
  while counter <= userDays:
    print(counter,  '\t', convertToDollars(sallaryOnDay(counter)))
    counter = counter + 1

  print("Total =", convertToDollars(moneyAccumulator(userDays)))
main()

这是我的错误:

Traceback (most recent call last):
  File "C:/Users/Colin/AppData/Local/Programs/Python/Python35-32/Assignment5Exercise2.py", line 42, in <module>
    main()
  File "C:/Users/Colin/AppData/Local/Programs/Python/Python35-32/Assignment5Exercise2.py", line 38, in main
    print(counter,  '\t', convertToDollars(sallaryOnDay(counter)))
  File "C:/Users/Colin/AppData/Local/Programs/Python/Python35-32/Assignment5Exercise2.py", line 30, in convertToDollars
    return moneyInDollars

UnboundLocalError:赋值前引用的局部变量'moneyInDollars'

无论出于何种原因,convertToDollarsmoneyAccumulator生成的值上使用时都有效,而sallaryOnDay则无效。

3 个答案:

答案 0 :(得分:1)

如果这个条件没有通过:

if moneyInCents >= 100:

然后moneyInDollars将被定义。您可以通过在if语句之前使用默认值声明它来轻松修复此问题:

def convertToDollars(moneyInCents):
  moneyInDollars = 0
  if moneyInCents >= 100:
    moneyInDollars = moneyInCents/100

  return moneyInDollars

答案 1 :(得分:0)

z = 1

如果def convertToDollars(moneyInCents): if moneyInCents >= 100: moneyInDollars = moneyInCents/100 return moneyInDollars 不成立,moneyInCents >= 100永远不会被分配,因此是未知的变量名称。

答案 2 :(得分:0)

考虑moneyInCents小于import pandas as pd df = pd.DataFrame({'Value': y}, index=pd.to_datetime(x)) # Value #2016-10-06 0 #2016-10-07 1 #2016-10-10 2 #2016-10-11 3 #2016-10-12 4 df.reindex(pd.date_range(start = df.index.min(), end = df.index.max())) # Value #2016-10-06 0.0 #2016-10-07 1.0 #2016-10-08 NaN #2016-10-09 NaN #2016-10-10 2.0 #2016-10-11 3.0 #2016-10-12 4.0 的情况,它不会进入你的状态,并且你试图返回100而没有声明它或为其分配默认值。< / p>

要解决这个问题,请在条件之前声明它,并给它一些默认值:

moneyInDollars

但是,考虑到您希望转换为美元,如果金额低于100,您就没有理由不给出美元金额。

def convertToDollars(moneyInCents):
  moneyInDollars = 0
  if moneyInCents >= 100:
    moneyInDollars = moneyInCents/100

  return moneyInDollars

演示:

def convertToDollars(moneyInCents):
    return moneyInCents/100