这是我的密码
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
产生的值。在
如果
moneyInCents >= 100
不为真,moneyInDollars
永远不会被赋值,因此是一个未知的变量名。在考虑这样一个场景,moneyInCents小于
100
,它将不符合您的条件,并且您试图返回moneyInDollars
,而没有声明它或为其分配默认值。在要解决这个问题,请在条件之前声明它,并给它一些默认值:
然而,考虑到你想兑换成美元,如果美元少于100美元,你就没有理由不能给出。在
^{pr2}$演示:
如果此条件不通过:
if moneyInCents >= 100:
则
moneyInDollars
将未定义。通过在if语句之前声明默认值,可以轻松解决此问题:相关问题 更多 >
编程相关推荐