简体   繁体   中英

Using Python while loop to make an API call

I'm a beginner Python learner and I'm trying to figure out how to use a while loop for a project where the user can input a location and get the weather for that location. My code so far does this fine for the first input, but it just reprints the same data when I try to look up a different city. I'm stuck on how to get the program to "reset" so that the user can input a new location. This is what I have so far:

import json, requests

base_url = "sampleurl"
appid = "1a2b3c4d5e6f"
city = input("Enter a city or zip code: ")

url = f"{base_url}?q={city}&units=imperial&APPID={appid}"
print(url)
print()

response = requests.get(url)
#JSON response formats the unformatted data
unformatted_data = response.json()

temp = unformatted_data["main"]["temp"]
print(f"The current temperature is: {temp}")

temp_max = unformatted_data["main"]["temp_max"]
print(f"The maximum temperature is: {temp_max}")
print()

while True:
#not sure where to put the request response or if I'm doing it completely wrong in this part
  city = input("Enter a zip code or city or enter 9 to end the program: ")
  print(url)
  print()

  url = f"{base_url}?q={city}&units=imperial&APPID={appid}"
  print(url)
  print()

response = requests.get(url)
unformatted_data = response.json()
print()

if city:
    print(f"The current temperature is: {temp}")
    print(f"The maximum temperature is: {temp_max}")
    print()
#After the first time the user inputs a city, the following outputs remain the same as the first inputted city.

You could use the input only inside the while loop. Also, you need to move temp and temp_max to the while loop. Your code should look like this:

import requests

base_url = "sampleurl"
appid = "1a2b3c4d5e6f"


while True:
    #not sure where to put the request response or if I'm doing it completely wrong in this part
    city = input("Enter a zip code or city or enter 9 to end the program (type 'leave' to leave): ")
    url = f"{base_url}?q={city}&units=imperial&APPID={appid}"
    print(url)
    print()
    if city == 'leave':
        break


    response = requests.get(url)
    unformatted_data = response.json()
    print()

    if city:
        temp = unformatted_data["main"]["temp"]
        print(f"The current temperature is: {temp}")

        temp_max = unformatted_data["main"]["temp_max"]
        print(f"The maximum temperature is: {temp_max}")
        print()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM