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...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing class and display a list of * houses sorted by the house's listing number * * Complete the code below the numbered comments, 1 - 4. DO NOT CHANGE the * pre-written code * @author * */ public class HouseListingDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); HouseListing[] list; String listNumber, listDesc; int count = 0; double listPrice; String...
JAVA - Complete the directions in the 5 numbered comments import java.util.Scanner; /** * This program...
JAVA - Complete the directions in the 5 numbered comments import java.util.Scanner; /** * This program will use the HouseListing class and display a list of * houses sorted by the house's listing number * * Complete the code below the numbered comments, 1 - 4. DO NOT CHANGE the * pre-written code * @author * */ public class HouseListingDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); HouseListing[] list; String listNumber, listDesc; int count =...
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...
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...
Summary In this lab, you complete a prewritten Java program that calculates an employee’s productivity bonus...
Summary In this lab, you complete a prewritten Java program that calculates an employee’s productivity bonus and prints the employee’s name and bonus. Bonuses are calculated based on an employee’s productivity score as shown below. A productivity score is calculated by first dividing an employee’s transactions dollar value by the number of transactions and then dividing the result by the number of shifts worked. Productivity Score Bonus <=30 $50 31–69 $75 70–199 $100 >= 200 $200 Instructions Ensure the file...
Write a complete Java program, including import statements, variable declarations and initializations as needed, for the...
Write a complete Java program, including import statements, variable declarations and initializations as needed, for the following problem. DO NOT USE ARRAYS. The program will read from the keyboard a series of records, each record containing a city ID number (integer), morning temperature (integer) and evening temperature (integer). See below for sample input. Sample input: 123 72 79 157 80 100 103 76 56 9999 For each city ID read in, compute the average of the two temperatures. Print a...
Develop a program that calculates the final score and the average score for a student from...
Develop a program that calculates the final score and the average score for a student from his/her (1)class participation, (2) test, (3) assignment, (4) exam, and (5) practice scores. The user should enter the name of the student and scores ranging from 0 to 100 for each grading item. The final score is the sum of all grading items. The average score is the average of all grading items. Here is a sample output of the program: Enter the Student's...
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT