Question

In: Computer Science

*** Using Python *** Your program must prompt the user for their city or zip code...

*** Using Python ***

Your program must prompt the user for their city or zip code and request weather forecast data from openweathermap.org. Your program must display the weather information in an READABLE format to the user.

Requirements:

  • Create a Python Application which asks the user for their zip code or city.
  • Use the zip code or city name in order to obtain weather forecast data from: http://openweathermap.org/
  • Display the weather forecast in a readable format to the user.
  • Use comments within the application where appropriate in order to document what the program is doing.
  • Use functions including a main function.
  • Allow the user to run the program multiple times.
  • Validate whether the user entered valid data. If valid data isn’t presented notify the user.
  • Use the Requests library in order to request data from the webservice.
  • Use Python 3.
  • Use try blocks when establishing connections to the webservice. You must print a message to the user indicating whether or not the connection was successful.

*** also formatted into imperial units. Site defaults into Kelvin. ***

Solutions

Expert Solution

Important: First get your api key from openweathermap.org/ and paste it in line 9 in the code below,

Code

import requests

# make call to weboste and fetch data


def get_web_data(zip=None, city=None):
baseUrl = "http://api.openweathermap.org/data/2.5/weather?units=imperial"
# api id for the site
apiid = "" #enter api code here

# check if the suer gave the zip code or the city name
if zip is not None:
# us at the end id for usa country , change it as required
baseUrl += "&zip="+str(zip)+",us"
else:
baseUrl += "&q="+str(city)+",us"
# finally append the api id
baseUrl += "&appid="+str(apiid)
# make get requetss using requests module
r = requests.get(baseUrl)
# return the response
return r

# show data in human readabale format


def display(resp):
# this means request was successfull
if resp.status_code == 200:
data = resp.json()
print(f"""{data['name']} Weather Forecast:
Type: {data['weather'][0]['description']}
Wind Speed : {data['wind']['speed']} miles/hr
Visibility : {data['visibility']} m
Min. Temp : {data['main']['temp_min']} F
Max Temp : {data['main']['temp_max']} F
""")
else:
print("Request Failed, Error : ", resp.status_code)


def main():
while True:
# ask the user for his/her choice
choice = int(
input("How do you want to search ? :\n1. By Zip Code\n2. By City Name\n3. Exit\n"))

if choice == 1:
# ask for zip code
try:
# ask for zip code
zCode = int(input("Enter zip code : "))
# fetch data from website
resp = get_web_data(zCode, None)
display(resp)
except Exception as ex:
print("Error : ", ex)
elif choice == 2:
try:
cname = input("Enter city name : ")
# mak call to fetch fetch_data
resp = get_web_data(None, cname)
display(resp)
except Exception as ex:
print("Error : ", ex)
elif choice == 3:
break
else:
print("Invalid Choice..\n")


if __name__ == "__main__":
main()

Screenshot

Output


Related Solutions

In Python, your program will read in a number (no need to prompt the user), and...
In Python, your program will read in a number (no need to prompt the user), and then reads in that number of lines from the terminal. Then the program should print an array of strings formatted in a nice regular box. So if the user inputs this: 5 Grim visaged war has smooth’d his wrinkled front And now, instead of mounting barded steeds To fright the souls of fearful adversaries He capers nimbly in a lady’s chamber To the lascivious...
The code that creates this program using Python: Your program must include: You will generate a...
The code that creates this program using Python: Your program must include: You will generate a random number between 1 and 100 You will repeatedly ask the user to guess a number between 1 and 100 until they guess the random number. When their guess is too high – let them know When their guess is too low – let them know If they use more than 5 guesses, tell them they lose, you only get 5 guesses. And stop...
Python Code: Write a program to prompt the user to enter a first name, last name,...
Python Code: Write a program to prompt the user to enter a first name, last name, student ID, number of hours completed and GPA for 5 students. Use a loop to accept the data listed below. Save the records in a text file. Write a second program that reads the records from your new text file, then determines if the student qualifies for Dean’s list or probation. Display the records read from the file on screen with appropriate headings above...
Program must use Python 3 Your program must have a welcome message for the user. Your...
Program must use Python 3 Your program must have a welcome message for the user. Your program must have one class called CashRegister. Your program will have an instance method called addItem which takes one parameter for price. The method should also keep track of the number of items in your cart. Your program should have two getter methods. getTotal – returns totalPrice getCount – returns the itemCount of the cart Your program must create an instance of the CashRegister...
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and...
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and a menu of options for the user to choose from. Welcome to the Email Analyzer program. Please choose from the following options: Upload text data Find by Receiver Download statistics Exit the program Program Options Option 1: Upload Text Data If the user chooses this option, the program will Prompt the user for the file that contains the data. Read in the records in...
CODE IN PYTHON: Your task is to write a simple program that would allow a user...
CODE IN PYTHON: Your task is to write a simple program that would allow a user to compute the cost of a road trip with a car. User will enter the total distance to be traveled in miles along with the miles per gallon (MPG) information of the car he drives and the per gallon cost of gas. Using these 3 pieces of information you can compute the gas cost of the trip. User will also enter the number of...
Python: I want to make the following code to prompt the user if want to run...
Python: I want to make the following code to prompt the user if want to run the software again. I am new to python, so i do not know if it works like c++. If can explain that would be much appreciated base = float(input("Enter base of the triagle: ")) Triangle_Right = float(input("Enter right side of the triagle: ")) Triangle_Left = float(input("Enter left side of the triagle: ")) height = float(input("Enter the height of the triangle: ")) perimiter = base...
Description Your program must start and keep dialog with the user. Please create the first prompt...
Description Your program must start and keep dialog with the user. Please create the first prompt for the dialog. After that your program must accept the user’s response and echo it (output to screen) in upper case and adding the question mark at the end. The program must run endlessly until the user say “stop” in any combination of cases. Then you program must say “GOODBYE!” and quit. Example: HELLO, I AM THE PROGRAM Hi, I am Michael HI, I...
C++ code a program should prompt the user for the name of the output file. The...
C++ code a program should prompt the user for the name of the output file. The file should be opened for write operations. Values calculated by the program will be written to this file. The program must verify that the file opened correctly. If the file did not open, an error message should be printed and the user should be prompted again. This should continue until the user supplies a valid filename.
Create a python program that will: prompt a user for a command Command get_data Level 1:...
Create a python program that will: prompt a user for a command Command get_data Level 1: Take one of the commands my_max my_min my_range my_sum mean median mode fib factorize prime Requirements: Your commands should be case-insensitive You should use python lists to store data You should NOT use built-in python math functions, or math libraries to compute these values Tips: Write one function that will convert a string with comma-separated numbers into a python list with the numbers. You...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT