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

2024-10-01 22:32:27 发布

您现在位置: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()

我的错误是:

^{pr2}$

UnboundLocalError:赋值前引用了局部变量“moneyInDollars”

无论出于什么原因,convertToDollars在使用moneyAccumulator产生的值时起作用,而不是由sallaryOnDay产生的值。在


Tags: returnmaindefcounterprintwhileincomenumdays
3条回答
def convertToDollars(moneyInCents):
    if moneyInCents >= 100:
        moneyInDollars = moneyInCents/100
    return moneyInDollars

如果moneyInCents >= 100不为真,moneyInDollars永远不会被赋值,因此是一个未知的变量名。在

考虑这样一个场景,moneyInCents小于100,它将不符合您的条件,并且您试图返回moneyInDollars,而没有声明它或为其分配默认值。在

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

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

  return moneyInDollars

然而,考虑到你想兑换成美元,如果美元少于100美元,你就没有理由不能给出。在

^{pr2}$

演示:

print(convertToDollars(40))
# 0.4
print(convertToDollars(140))
# 1.4

如果此条件不通过:

if moneyInCents >= 100:

moneyInDollars将未定义。通过在if语句之前声明默认值,可以轻松解决此问题:

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

  return moneyInDollars

相关问题 更多 >

    热门问题