Python中的CurrencyConverter。错误'金额'未定义,为什么? 。还有是写这个代码更短或更紧凑的方式?

from currency_converter import CurrencyConverter 

我试图globalling达修复我的错误,但它并没有帮助货币的的Python中的CurrencyConverter。错误'金额'未定义,为什么? 。还有是写这个代码更短或更紧凑的方式?

global amounts 

c = CurrencyConverter()

currency = input('What ?')

currency = currency.split()

名单以供选择,字典

currencys = {"pounds":"GBP" , "dollars":"USD" , "euros":"EUR"} 

WCurrency = ' '

这是它承认句话是什么

if 'what' in currency: 

next_word = currency[currency.index('what') + 1]

if next_word == 'is':

长的if语句我想是笑rtened如果可能的话

 if 'pounds' in currency: 

amounts = currency[currency.index('pounds') - 1]

WCurrency = currencys['pounds']

if 'euros' in currency:

amounts = currency[currency.index('euros') - 1]

WCurrency = currencys['euros']

if 'dollars' in currency:

amounts = currency[currency.index('dollars') - 1]

WCurrency = currencys['dollars']

if 'in' in currency:

next_word = currency[currency.index('in') + 1]

if next_word == 'dollars':

W2Currency = currencys['dollars']

if next_word == 'pounds':

W2Currency = currencys['pounds']

if next_word == 'euros':

W2Currency = currencys['euros']

这可以让你输入的句子以不同的格式

if 'how' in currency: 

next_word = currency[currency.index('how') + 1]

if next_word == 'many':

长,如果可能的话

 if 'pounds' in currency: 

W2Currency = currencys['pounds']

if 'euros' in currency:

W2Currency = currencys['euros']

if 'dollars' in currency:

W2Currency = currencys['dollars']

if 'is' in currency:

next_word = currency[currency.index('is') + 1]

if next_word == 'dollars':

amounts = currency[currency.index('dollars') - 1]

WCurrency = currencys['dollars']

if next_word == 'pounds':

amounts = currency[currency.index('pounds') - 1]

WCurrency = currencys['pounds']

if next_word == 'euros':

amounts = currency[currency.index('euros') - 1]

WCurrency = currencys['euros']

def convertCurrency(amount, currency, targertCurrency):

try:

return c.convert(amount , currency , targertCurrency)

except:

print('Invalid currency or amounts!')

print(convertCurrency(amounts, str(WCurrency), str(W2Currency)))

回答:

使用elif这样可以防止美元,缩短陈述我想从再次被认可。这也是很好的做法。即

if 'pounds' in currency: 

amounts = currency[currency.index('pounds') - 1]

WCurrency = currencys['pounds']

elif 'euros' in currency:

amounts = currency[currency.index('euros') - 1]

WCurrency = currencys['euros']

elif 'dollars' in currency:

amounts = currency[currency.index('dollars') - 1]

WCurrency = currencys['dollars']

elif 'in' in currency:

next_word = currency[currency.index('in') + 1]

elif next_word == 'dollars':

W2Currency = currencys['dollars']

elif next_word == 'pounds':

W2Currency = currencys['pounds']

elif next_word == 'euros':

W2Currency = currencys['euros']

这意味着,如果dollarspounds处于森泰斯它将识别的第一个。唉这个代码非常混乱,我会建议使用for循环。即

for word in sentance: 

if word is in [list, of, currencies] and isdigit(sentance(word.index() - 1)):

currency = word

等等...

以上是 Python中的CurrencyConverter。错误'金额'未定义,为什么? 。还有是写这个代码更短或更紧凑的方式? 的全部内容, 来源链接: utcz.com/qa/258557.html

回到顶部