UnboundLocalError:在使用csv文件时局部变量被引用前未赋值
我在做一个货币转换器,但遇到了错误,首先打印出
sorry not a valid currency
然后是
Pound Sterling
Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: 'Euro'
1.22
Please enter the currency you would like to convert to: 'Pound Sterling'
Sorry, that is not a valid currency
81.9672131148
接着出现了一个本地变量错误
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
2 个回答
0
在这种情况下,如果表达式:
if currency == newCurrency
的结果是假的,那么在下面这条不带条件的语句中:
newAmount = int(toPound)*float(newRt)
试图访问的变量 newRt 还没有被初始化,因此会出现错误。
(补充)正如马丁所建议的,你应该在下面加一个返回语句:
print("Sorry, that is not a valid currency")
这意味着现在代码应该像这样:
print("Sorry, that is not a valid currency")
return
1
newRt
只有在 exchReader
中有数据行,并且某一行的 currency == newCurrency
为 True
时才会被设置。
因为后面的代码在没有匹配的货币时是无法合理运行的,所以在这个时候就直接返回吧:
else:
print("Sorry, that is not a valid currency")
return
你在 exchReader
中没有数据行的原因是,你不能对 CSV 读取器进行 两次 循环;你最好把文件中的所有数据存储到一个字典里:
with open('exchangeRate.csv') as exRtFile:
exchReader = csv.reader(exRtFile)
currencies = {row[0]: float(row[1]) for row in extchReader}
crntCurrency = input("Please enter the current currency: ")
if crntCurrency not in currencies:
print("Sorry, that is not a valid currency")
return
newRt = currencies[newCurrency]
toPound = crntAmnt / crntRt
print(toPound)
newAmount = int(toPound) * newRt
print("You have: ", newAmount, newCurrency)