做一个货币兑换器,但我有一个错误,首先打印
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
如果在}。在
exchReader
中有行,newRt
是设置的,而对于一行,if currency == newCurrency
是{由于在没有匹配货币的情况下无法正常运行其余代码,因此只需在该点返回:
在
^{pr2}$exchReader
中没有行的原因是您不能在CSV读取器上循环两次;最好将文件中的所有数据存储在字典中:如果表达式:
将试图在中访问的变量newRt求值为false 无条件(即每次都执行)语句:
^{pr2}$未初始化,因此 将引发错误
(编辑)正如Martin建议的那样,您应该在下面添加一个return语句:
这意味着现在它应该是这样的:
相关问题 更多 >
编程相关推荐