0

I am facing this error while trying to run this program

KeyError                                  Traceback (most recent call last)
<ipython-input-6-f0146e24a603> in <cell line: 16>()
     14 
     15 # Call the function to calculate total amount
---> 16 total_amount = calculate_amount(coins)
     17 
     18 # Print the total amount in dollars

1 frames
<ipython-input-6-f0146e24a603> in <listcomp>(.0)
      5 
      6     # Calculate the total amount in dollars
----> 7     total_amount = sum([coin_values[k]*v for k, v in enumerate(coins) if v > 0])
      8 
      9     # Return the total amount in dollars

KeyError: 0

This is the code that I am working on but, not able to solve the error.

# Function to calculate total amount from coins received
def calculate_amount(coins):
    # Dictionary to map each coin to its value in dollars
    coin_values = {10: 0.1, 20: 0.2, 50: 0.5, 1: 1, 2: 2}

    # Calculate the total amount in dollars
    total_amount = sum([coin_values[k]*v for k, v in enumerate(coins) if v > 0])

    # Return the total amount in dollars
    return total_amount

# Take input from user
coins = list(map(int, input().split()))

# Call the function to calculate total amount
total_amount = calculate_amount(coins)

# Print the total amount in dollars
print("%.2f dollar" % total_amount)
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
  • 1
    Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – mkrieger1 Apr 03 '23 at 10:20
  • Maybe you wanted to do, simple `[coin_values[v] * v for v in coins if v > 0]` – kiner_shah Apr 03 '23 at 10:21
  • To iterate over key-value pairs, use `coins.items()`, not `enumerate(coins)`. – mkrieger1 Apr 03 '23 at 10:31

0 Answers0