Question

This is a python question. Start with this program, import json from urllib import request def...

This is a python question.

Start with this program,

import json
from urllib import request


def main():
    to_continue = 'Yes'
    while to_continue == 'yes' or to_continue == 'Yes':
        currency_code = input("Enter currency code: ").upper()
        dollars = int(input("Enter number of dollar you want to convert: "))
        # calling the exchange_rates function
        data = get_exchange_rates()
        if currency_code in data["rates"].keys():
            currency = data["rates"][currency_code]
            # printing the the currency value  by multiplying the dollars amount.
            print("The value is:", str(currency * dollars))
        else:
            print("Error: the conversion can't be done it")
        to_continue = input(f"would you like to continue, enter 'Yes' or 'No' ")


# You do not need to modify any code below here.

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 dictionry
        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 there exchange rates api 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()

This program fetches data every time the user wants to make a conversion. But, the exchange rates don't change very fast, so the program may fetch the same data over and over again.

For this question, shelve the exchange rates to a file with today's date in the name. When the program loads, if there is a file with today's date in the name, then read the exchange rate data dictionary from that file and use it in your program.

If there is no shelf file with today's date in the name, then call the get_exchange_rates() function to get the most recent data from exchangeratesapi.io.

Storing recently used data to save fetching data from a store is called caching, and it's common in many areas of computing.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have attached the code below. If you have any problem, feel free to discuss.

Program Screenshot:

Sample Output:

Program Code to copy:

import json
from urllib import request
from datetime import datetime

def main():
    to_continue = 'Yes'
    while to_continue == 'yes' or to_continue == 'Yes':
        currency_code = input("Enter currency code: ").upper()
        dollars = int(input("Enter number of dollar you want to convert: "))
        # calling the exchange_rates function
        # we will store latest exchange rates in a file called exchange_rates.json
        cachefilename = "exchange_rates.json"
        try:
            with open(cachefilename) as f:
                data = json.load(f)
                #match current data date
                if datetime.utcnow().date().isoformat() != data['date']:
                    data = get_exchange_rates()
        except FileNotFoundError:
            data = get_exchange_rates()
        if currency_code in data["rates"].keys():
            currency = data["rates"][currency_code]
            # printing the the currency value by multiplying the dollars amount.
            print("The value is:", str(currency * dollars))
        else:
            print("Error: the conversion can't be done it")
        to_continue = input(f"would you like to continue, enter 'Yes' or 'No' ")
    ##dump file
    with open(cachefilename , 'w') as f:
        json.dump(data , f)

# You do not need to modify any code below here.

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 dictionry
        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 there exchange rates api 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()

Add a comment
Know the answer?
Add Answer to:
This is a python question. Start with this program, import json from urllib import request def...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is a python question. from urllib import request import json """ Complete this program that...

    This is a python question. from urllib import request import json """ Complete this program that calculates conversions between US dollars and other currencies. 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...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file...

    Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following: How to format each dictionary item as a text string in the input file. How to covert each input string into a dictionary item. How to format each item of your inverted dictionary as a text string in the output file. Create an input file with your original...

  • PYTHON PLEASE Write a function to censor words from a sentence code: def censor_words(sentence, list_of_words): """...

    PYTHON PLEASE Write a function to censor words from a sentence code: def censor_words(sentence, list_of_words): """ The function takes a sentence and a list of words as input. The output is the sentence after censoring all the matching words in the sentence. Censoring is done by replacing each character in the censored word with a * sign. For example, the sentence "hello yes no", if we censor the word yes, will become "hello *** no" Note: do not censor the...

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • Can you please enter this python program code into an IPO Chart? import random def menu():...

    Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...

  • I need this python program to access an excel file, books inventory file. The file called...

    I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...

  • Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from...

    Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs. txt, articles.txt, and prepositions.txt. (HINT: Define a single new function, getWords. This function should expect a filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list...

  • Solve the code below: CODE: """ Code for handling sessions in our web application """ from bottle import request, response import uuid import json import model import dbsche...

    Solve the code below: CODE: """ Code for handling sessions in our web application """ from bottle import request, response import uuid import json import model import dbschema COOKIE_NAME = 'session' def get_or_create_session(db): """Get the current sessionid either from a cookie in the current request or by creating a new session if none are present. If a new session is created, a cookie is set in the response. Returns the session key (string) """ def add_to_cart(db, itemid, quantity): """Add an...

  • DATA: # happy2.py import csv def main(): happy_dict = make_happy_dict() print_sorted_dictionary(happy_dict) def make_happy_dict(): filename = "happiness.csv"...

    DATA: # happy2.py import csv def main(): happy_dict = make_happy_dict() print_sorted_dictionary(happy_dict) def make_happy_dict(): filename = "happiness.csv" happy_dict={} with open(filename, 'r') as infile: csv_happy = csv.reader(infile) infile.readline() for line in csv_happy: happy_dict[line[0]] = line[2]       return happy_dict def lookup_happiness_by_country(happy_dict): return def print_sorted_dictionary(D): if type(D) != type({}): print("Dictionary not found") return print("Contents of dictionary sorted by key.") print("Key","Value") for key in sorted(D.keys()): print(key, D[key]) main() "happines.csv" Country,Year of Estimate,Happiness Index Afghanistan,2018,2.694303274 Albania,2018,5.004402637 Algeria,2018,5.043086052 Angola,2014,3.794837952 Argentina,2018,5.792796612 Armenia,2018,5.062448502 Australia,2018,7.17699337 Austria,2018,7.396001816 Azerbaijan,2018,5.167995453 Bahrain,2017,6.227320671 Bangladesh,2018,4.499217033...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT