我有以下代碼使用3個字符串'我們美元','歐元','02 -11-2014', 和一個數字來計算該給定日期的匯率。我修改了 代碼通過這些參數,但我得到一個錯誤,當我嘗試用Python - NameError
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
調用它,我是相當新的Python的,所以我的知識是有限的。任何幫助將不勝感激。謝謝。 另外我使用的Python版本是3.4.2。
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
你能提供完整的錯誤嗎?包括引發錯誤和錯誤信息的行? – 2014-11-02 14:14:52
在最後一行你使用變量currTo,currFrom,currAmount和currDate,但是這些變量還沒有被初始化。 – user38034 2014-11-02 14:17:20