[英]KeyError Dictionary Conversion Python
我想創建一個程序,將錢從一種貨幣轉換為另一種貨幣。 到目前為止,這是我的代碼:
def read_exchange_rates(exchange_file_name):
#reads file with exchange rates formatted like USD,1. Each line is a 3 letter currency code and a float to convert it to USD.
f=open(exchange_file_name,"r")
answer={}
for line in f:
k, v = line.split(",")
answer[k] = float(v)
return answer
f.close()
pass
class Money:
exchange_rates = read_exchange_rates(rate_file)
#calls previously defined function to read file with exchange rates
def __init__ (self, monamount, code):
self.monamount=monamount
self.code=code
def to(self, othercode):
i = self.monamount/self.exchange_rates[self.code]
j = i*self.exchange_rates[self.othercode]
return othercode+str(j)
它應返回轉換后的金額以及其貨幣代碼(其他代碼),但應返回KeyError。 如果我輸入
a=Money(650,'USD')
b=a.to('GBP')
它應該返回GBP somenumber。 這是錯誤。 謝謝!
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
b=a.to('GBP')
File "<pyshell#124>", line 9, in to
i = self.monamount/self.exchange_rates[self.code]
KeyError: 'USD'
您確定文件中包含“ USD”密鑰嗎?
這是經過稍微修改和簡化的代碼(因此,我不必創建交換文件):
def read_exchange_rates():
answer={}
answer['USD'] = 1
answer['GBP'] = 0.76
return answer
class Money:
exchange_rates = read_exchange_rates()
def __init__ (self, monamount, code):
self.monamount = monamount
self.code = code
def to(self, othercode):
i = self.monamount/self.exchange_rates[self.code]
j = i*self.exchange_rates[othercode]
return othercode + str(j)
a = Money(650,'USD')
b = a.to('GBP')
print(b)
打印出GBP494.0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.