UnboundLocalError:在使用csv-fi赋值之前引用了局部变量

2024-09-19 23:31:03 发布

您现在位置:Python中文网/ 问答频道 /正文

做一个货币兑换器,但我有一个错误,首先打印

sorry not a valid currency

之后

^{pr2}$

然后是局部变量错误

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in ?
    converter()
  File "//server01/ICT2124/Task 1/Currency Converter 2.py", line 19, in converter
    exchange()
  File "//server01/ICT2124/Task 1/Currency Converter 2.py", line 65, in exchange
    newAmount = int(toPound)*float(newRt)
UnboundLocalError: local variable 'newRt' referenced before assignment
>>>

这是密码,请帮忙

def exchange():
    crntAmnt = int(input("Please enter the amount of money to convert: "))
    print(currencies)
    exRtFile = open ('exchangeRate.csv')
    exchReader = csv.reader(exRtFile)
    crntCurrency = input("Please enter the current currency: ")
    for row in exchReader:
            currency = row[0]
            if currency == crntCurrency:
                crntRt = row[1]
                print(crntRt)
                break
    else:
        print("Sorry, that is not a valid currency")


    newCurrency = input("Please enter the currency you would like to convert to: ")
    for row in exchReader:
            currency = row[0]
            if currency == newCurrency:
                newRt = row[1]
                print(newRt)
                break
    else:
        print("Sorry, that is not a valid currency")


    toPound = crntAmnt/float(crntRt)
    print(toPound)
    newAmount = int(toPound)*float(newRt)
    print("You have: " ,newAmount, newCurrency,)
    return

Tags: ininputexchangelinenotfloatcurrencyfile
2条回答

如果在exchReader中有行,newRt设置的,而对于一行,if currency == newCurrency是{}。在

由于在没有匹配货币的情况下无法正常运行其余代码,因此只需在该点返回:

else:
    print("Sorry, that is not a valid currency")
    return

exchReader中没有行的原因是您不能在CSV读取器上循环两次;最好将文件中的所有数据存储在字典中:

^{pr2}$

如果表达式:

if currency == newCurrency

将试图在中访问的变量newRt求值为false 无条件(即每次都执行)语句:

^{pr2}$

未初始化,因此 将引发错误

(编辑)正如Martin建议的那样,您应该在下面添加一个return语句:

print("Sorry, that is not a valid currency")

这意味着现在它应该是这样的:

print("Sorry, that is not a valid currency")
return

相关问题 更多 >