Question

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 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():

print('Remove this print statement, and then write your code here.')

# 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 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()

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

Python3:

code:

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 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():
   choice='y'
   while choice=='y' or choice=='Y':
       cur_code=input("Enter currency code: ").upper()
       dollars=int(input("Enter number of dollar you want to convert: ").strip())
       data=get_exchange_rates()
       if cur_code in data["rates"].keys():
           curcodevsdollar=data["rates"][cur_code]
           print("The value is:",str(round(curcodevsdollar*dollars,2)))
       else:
           print("Error: Unable to find currency code")
       choice=input("Do you want to exit(y/n)")
   # 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
       return data
   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 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()

Sample i/O;

Reference for indendation:

Explanation:

Sample i/o and indendation reference is provided for your understanding.

**Please upvote if you like the answer

Add a comment
Know the answer?
Add Answer to:
This is a python question. from urllib import request import json """ Complete this program that...
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. 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...

  • Assignment Overview This assignment will give you more experience on the use of strings and iterations....

    Assignment Overview This assignment will give you more experience on the use of strings and iterations. The goal of this project is to use Google’s currency converter API to convert currencies in Python and display the result to user by processing the returned results. Assignment Background The acronym API stands for “Application Programming Interface”. It is usually a series of functions, methods or classes that supports the interaction of the programmer (the application developer, i.e., you) with some particular program....

  • 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...

  • -----------Python program------------------- Instructions: For this assignment, you will write complete a program that allows a customer...

    -----------Python program------------------- Instructions: For this assignment, you will write complete a program that allows a customer to plan for retirement. Part 2: Generate a Retirement Planning Table: It's hard to decide how much you need to save for retirement. To help your customer visualize how long her nest egg will last, write a program that allows the user to generate a retirement planning table showing the number of months the savings will last for various combinations of starting account balance...

  • (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that...

    (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that you have been provided on Canvas. That file has a name and 3 grades on each line. You are to ask the user for the name of the file and how many grades there are per line. In this case, it is 3 but your program should work if the files was changed to have more or fewer grades per line. The name and...

  • using this code to complete. it python 3.#Display Program Purpose print("The program will show how much...

    using this code to complete. it python 3.#Display Program Purpose print("The program will show how much money you will make working a job that gives a inputted percentage increase each year") #Declaration and Initialization of Variables userName = "" #Variable to hold user's name currentYear = 0 #Variable to hold current year input birthYear = 0 #Variable to hold birth year input startingSalary = 0 #Variable to hold starting salary input retirementAge = 0 #Variable to hold retirement age input...

  • 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!")...

  • PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold...

    PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold a dictionary or sets - must define a function that accepts dictionaries or sets as an argument A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. For e.g.: a dictionary defined as: released = { "iphone" : 2007, "iphone 3G": 2008, "iphone 3GS": 2009, "iphone 4" : 2010,...

  • In python using a def main() function, Write a function that will print a hello message,...

    In python using a def main() function, Write a function that will print a hello message, then ask a user to enter a number of inches (should be an integer), and then convert the value from inches to feet. This program should not accept a negative number of inches as an input. The result should be rounded to 2 decimal places(using the round function) and printed out on the screen in a format similar to the example run. Use a...

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