Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would use:</p> <ul> <li>A dictionary to validate and normalize currency, rather than ad-hoc lists</li> <li>A loop to get valid input from the user, rather than recursion</li> <li>The <code>.lower()</code> method to normalize case</li> </ul> <p>My refactored version:</p> <pre><code>CURRENCY = { '¥': 'JPY', 'yen': 'JPY', 'jpy': 'JPY', '€': 'EUR', 'euro': 'EUR', 'eur': 'EUR', '$': 'USD', 'dollar': 'USD', 'usd': 'USD', '£': 'GBP', 'pound': 'GBP', 'gbp': 'GBP', } def read_currency(prompt): """Prompt the user to enter a currency. Returns a currency code. """ while True: x = input(prompt) try: return CURRENCY[x.lower()] except KeyError: print('Unknown currency: {!r}'.format(x)) </code></pre> <p>You can then calculate conversion rates how you like:</p> <pre><code>from decimal import Decimal RATES = { 'JPY': Decimal("0.010589"), 'EUR': Decimal("1.2983"), 'GBP': Decimal("1.5228"), 'USD': Decimal("1.0000"), } def conversion_rate(cur1, cur2): """Get the conversion rate from currency 1 to currency 2.""" return RATES[cur1] / RATES[cur2] </code></pre> <p>And here is code for the conversion:</p> <pre><code>amount = Decimal(input('Enter amount: ')) currency1 = read_currency('Enter source currency: ') currency2 = read_currency('Enter target currency: ') rate = conversion_rate(currency1, currency2) print('{} {} is equal to {} {}' .format(currency1, amount, currency2, amount * rate)) </code></pre> <p>Note that there are better rules for rounding you may want to apply.</p> <p>Example run:</p> <pre> Enter amount: 1450 Enter source currency: yen Enter target currency: $ JPY 1450 is equal to USD 15.3700 </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload