Question

In: Computer Science

from urllib import request import json """ Complete this program that calculates conversions between US dollars...

from urllib import request
import json

"""
Complete this program that calculates conversions between US dollars and other currencies. (Please use Pyton 3.8)

In your main function, start a loop.
In the loop, ask the user what currency code they would like to convert to
And, how many dollars they want to convert.

If you scroll down, you can see an example response with the available 3-letter currency codes.

Call the get_exchange_rates() function. 
This function returns a dictionary with another dictionary inside it. 
You'll need to get the exchange rate from the dictionary.

If the user enters a currency code that is not in the dictionary, your program should not crash.
It should print a message saying the code was not found, and repeat the loop so they can try again.

Then, do the math. For example, if the user wants to convert $100 to Euros (EUR), 
and the exchange rate is 0.874, then you need to multiply the US Dollar amount by 
the exchange rate to get the amount in Euros. So to convert $100 to Euro, 100 * 0.874 = 87.4 Euro.

Display the result to the user. Format the number to 2 decimal places.

Don't modify the get_exchange_rates function or the example_exchange_rates function. 
These functions get data from exchangeratesapi.io. If this site is not available or your 
computer is not online, then get_exchange_rates will return an example dictionary that is the 
same structure as the exchangeratesapi.io response. This is not an error - your program will
do the same thing for real data as it does for example data.

"""


def main():
    # TODO write your code inside this main function.
    print('Remove this print statement, and then write your code here.')




# You do not need to modify any code below here.  There's a call to main at very end of this file.

def get_exchange_rates():
    """" Connect to the exchangeratesapi.io server and request the latest exchange rates,
    relative to US Dollars.  Return the response as a dictionary. """

    url = 'https://api.exchangeratesapi.io/latest?base=USD'

    try:  # Attempt to connect to the exchangeratesapi server
        response = request.urlopen(url).read()   # and get the server's response
        data = json.loads(response)   # convert the response to a Python dictionary
        return data # return the dictionary
    except:  # this code runs if there's any error fetching data.
        # It returns some example data, that has the same structure as real data, to use instead
        # So it's no problem if you don't have an internet connection or the exchangeratesapi server is down.
        print('There was an error fetching real data. Perhaps you are offline? Returning example data.')
        return example_exchange_rates()


def example_exchange_rates():
    """ In case the exchangeratesapi.io is not available, the program will use this example data.
     This data has the same structure as real data, so your program doesn't need to worry if real data
     or example data is used. """
    example_data = {
       "base": "USD",
       "date": "2019-01-30",
       "rates": {
          "ISK": 119.8705048561,
          "CAD": 1.3221629189,
          "MXN": 19.0960713973,
          "CHF": 0.9977250853,
          "AUD": 1.3898853793,
          "CNY": 6.7168606177,
          "GBP": 0.7642050923,
          "USD": 1.0,
          "SEK": 9.0859217779,
          "NOK": 8.4817569341,
          "TRY": 5.2750021874,
          "IDR": 14130.0026249016,
          "ZAR": 13.6043398373,
          "HRK": 6.4953189255,
          "EUR": 0.8749671887,
          "HKD": 7.8451308076,
          "ILS": 3.6677749584,
          "NZD": 1.4632076297,
          "MYR": 4.1057835331,
          "JPY": 109.4408959664,
          "CZK": 22.5759034036,
          "SGD": 1.3510368361,
          "RUB": 65.9388397935,
          "RON": 4.1605564791,
          "HUF": 276.9533642488,
          "BGN": 1.7112608277,
          "INR": 71.1794557704,
          "KRW": 1118.1905678537,
          "DKK": 6.5314550704,
          "THB": 31.3798232566,
          "PHP": 52.3002887392,
          "PLN": 3.7540467232,
          "BRL": 3.7091609065
       }
    }

    return example_data


main()

Solutions

Expert Solution

from urllib import request
import json
def main():
# TODO write your code inside this main function.
again="y"
exchangeRates=get_exchange_rates()["rates"]
while again.lower()=="y":
code = input("Enter currency code to convert to: ")
if code not in exchangeRates:
print("The entered currency code was not found!! Please try for another one")
else:
amt = float(input('Enter dollar amount to convert: $'))
cnverted=amt*exchangeRates[code]
print("USD ${:.2} is equal to {:s} {:.2f}".format(amt,code,cnverted))
again = input("Do you want to enter again(y/n)?: ")
  
# You do not need to modify any code below here. There's a call to main at very end of this file.

def get_exchange_rates():
"""" Connect to the exchangeratesapi.io server and request the latest exchange rates,
relative to US Dollars. Return the response as a dictionary. """

url = 'https://api.exchangeratesapi.io/latest?base=USD'

try: # Attempt to connect to the exchangeratesapi server
response = request.urlopen(url).read() # and get the server's response
data = json.loads(response) # convert the response to a Python dictionary
return data # return the dictionary
except: # this code runs if there's any error fetching data.
# It returns some example data, that has the same structure as real data, to use instead
# So it's no problem if you don't have an internet connection or the exchangeratesapi server is down.
print('There was an error fetching real data. Perhaps you are offline? Returning example data.')
return example_exchange_rates()


def example_exchange_rates():
""" In case the exchangeratesapi.io is not available, the program will use this example data.
This data has the same structure as real data, so your program doesn't need to worry if real data
or example data is used. """
example_data = {
"base": "USD",
"date": "2019-01-30",
"rates": {
"ISK": 119.8705048561,
"CAD": 1.3221629189,
"MXN": 19.0960713973,
"CHF": 0.9977250853,
"AUD": 1.3898853793,
"CNY": 6.7168606177,
"GBP": 0.7642050923,
"USD": 1.0,
"SEK": 9.0859217779,
"NOK": 8.4817569341,
"TRY": 5.2750021874,
"IDR": 14130.0026249016,
"ZAR": 13.6043398373,
"HRK": 6.4953189255,
"EUR": 0.8749671887,
"HKD": 7.8451308076,
"ILS": 3.6677749584,
"NZD": 1.4632076297,
"MYR": 4.1057835331,
"JPY": 109.4408959664,
"CZK": 22.5759034036,
"SGD": 1.3510368361,
"RUB": 65.9388397935,
"RON": 4.1605564791,
"HUF": 276.9533642488,
"BGN": 1.7112608277,
"INR": 71.1794557704,
"KRW": 1118.1905678537,
"DKK": 6.5314550704,
"THB": 31.3798232566,
"PHP": 52.3002887392,
"PLN": 3.7540467232,
"BRL": 3.7091609065
}
}

return example_data


main()


Related Solutions

8. Complete the program that calculates the volume of a cube. If the side length entered...
8. Complete the program that calculates the volume of a cube. If the side length entered for the cube is negative, the program should display an error message saying the length should be positive. If the side length entered for the cube is greater than 100, the program should print a message saying the side is too big. Otherwise the program should calculate and print the volume of the cube of the given side length. Sample program runs are shown...
Program Name: Divisible. Write a program that calculates the number of integers in a range from...
Program Name: Divisible. Write a program that calculates the number of integers in a range from 1 to some user-specified upper bound that are divisible by 3, the sum of those integers, and the number and sum of those integers not divisible by 3. Your program must display meaningful output which includes: the selected upper bound number of integers divisible by 3 sum of integers divisible by 3 number of integers not divisible by 3 sum of integers not divisible...
jgrasp environment, java write a complete program that calculates a restaurant bill. Prompt the user for...
jgrasp environment, java write a complete program that calculates a restaurant bill. Prompt the user for the check amount, then ask the user what type of tipp they would like to leave: the choices are 1 for good tip (20%), 2 for an average tip (15%), or 3 for poor tip (10%). Use their input and an if-else to calculate the tip amount. Then calculate and output the final bill: check+tip print out the bill, exactly as shown (print the...
make a c++ program that calculates the amount left from a value of money of one...
make a c++ program that calculates the amount left from a value of money of one dollar bill or less in quarters, dimes, nickels, and pennies. The remaining value can be shown in cents knowing that in cents: penny = 1 nickel = 5 dime = 10 quarter = 25
The exchange rate between Pounds and US dollars is determined by the intersection of the demand...
The exchange rate between Pounds and US dollars is determined by the intersection of the demand and supply curves for euros in terms of dollars. Explain how an increase in US inflation relative to English inflation will effect equilibrium exchange rates.
Q1.Graph the demand for and supply of Australian dollars for US dollars. Label each axis. From...
Q1.Graph the demand for and supply of Australian dollars for US dollars. Label each axis. From Australia's perspective, show graphically and explain the effect on the Australian dollar of the following. Australia’s major trading partners experience higher RGDP and income growth resulting in an increase in the price of Australian exported commodities (e.g. coal, iron-ore). Additionally: -   there is increased speculation of the Australian dollar (AUD) based on speculators expectations of its future value. -   Lower interest rates in Australia...
Write a C program that calculates a worker’s wages from their hours worked and hourly rate....
Write a C program that calculates a worker’s wages from their hours worked and hourly rate. This wage calculator should also account for overtime hours, calculate amount to be witheld from taxes, and calculate the final net income. Required functionality: 1. Ask the user for the number of hours worked and hourly rate in dollars. The program should be able to accept decimal values for both of these (e.g. 3.2 hours, 11.25 dollars/hour) 2. Overtime hours are those worked in...
Write a MIPS Assembly language program to request a file name from the user, open the...
Write a MIPS Assembly language program to request a file name from the user, open the file, read the contents, and write out the contents to the console. This is what I have so far: .data    fileName:   .space 100    prompt1:   .asciiz "Enter the file name: "    prompt2:    .asciiz ""    prompt3:   .asciiz "\n"    buffer:    .space 4096 .text    main:        #        li $v0, 4        la $a0, prompt1       ...
- On April 17, 2018 the exchange rate between the Canadian dollar and the US dollars...
- On April 17, 2018 the exchange rate between the Canadian dollar and the US dollars was 1 CAD = 0.796 USD. On April 5, 2019 the exchange rate was 1 CAD = 0.780 USD. Did the Canadian dollar appreciate or depreciate and by what percent? (1 point) - Find the exchange rate in terms of US dollars per British pound if on April 5, 2019 the exchange rate between the US dollar and the Mexican peso was 1 USD...
This data shows the series of quarterly shipments in millions of US dollars of US hosehold appliances between 1985 and 1989.
Please show answers and code using R/R Studio. This data shows the series of quarterly shipments in millions of US dollars of US hosehold appliances between 1985 and 1989. Quarter Shipments Q1-1985 4009 Q1-1986 4123 Q1-1987 4493 Q1-1988 4595 Q1-1989 4245 Q2-1985 4321 Q2-1986 4522 Q2-1987 4806 Q2-1988 4799 Q2-1989 4900 Q3-1985 4224 Q3-1986 4657 Q3-1987 4551 Q3-1988 4417 Q3-1989 4585 Q4-1985 3944 Q4-1986 4030 Q4-1987 4485 Q4-1988 4258 Q4-1989 4533 (b) apply a moving average with window span w=4...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT