Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnboundLocalError:在使用csv文件分配之前引用的局部变量_Python_Csv_Python 3.x - Fatal编程技术网

Python UnboundLocalError:在使用csv文件分配之前引用的局部变量

Python UnboundLocalError:在使用csv文件分配之前引用的局部变量,python,csv,python-3.x,Python,Csv,Python 3.x,正在制作货币转换器,但我有一个错误,首先打印 sorry not a valid currency 之后 然后是局部变量错误 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

正在制作货币转换器,但我有一个错误,首先打印

sorry not a valid currency
之后

然后是局部变量错误

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
>>>
newRt
仅在
exhreader
中有行且
if 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)

如果表达式:

if currency == newCurrency
对试图在中访问的变量newRt求值为false 无条件(即每次都执行)声明:

newAmount = int(toPound)*float(newRt)
未初始化,因此为 错误将被提出

(编辑)正如Martin所建议的,您应该在以下项下添加返回语句:

print("Sorry, that is not a valid currency")
这意味着现在它应该是这样的:

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

@伍伯:这里没关系,是吗?具有多个参数的
print()
函数也不是线索:-P@MartijnPieters:他在
input()
的输入周围输入引号。这将在Python 2中生成正确的字符串(以错误的方式,被授予…),例如,
“'Euro'”
在Python 3.no中,因为这样我就无法更改并保存将要进行的更改later@user3165683:您稍后仍有一个
return
语句。@eryksun:我通过创建一个字典来说明整个问题。@eryksun:在这种情况下,另一个选项是首先要求两种货币,然后扫描CSV一次以查找两者。@eryksun:如果文件太大,您真的不想循环两次。我是一个初学者,不明白我在前面的“for”语句中初始化了,对吧,但我们可以这样说:varaible newRt仅在currency==newCurrency的情况下“获取”一个值。如果currency==newCurrency为False,那么newRt将没有任何值,并且当您稍后尝试访问它时,它将抛出一个错误
print("Sorry, that is not a valid currency")
print("Sorry, that is not a valid currency")
return