[Python] I need to reverse this block of codes functionality. Instead of Taking in zip codes...

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    # importing required libraries
    import requests
    import simplekml

    # defining important variables
    kml = simplekml.Kml()
    zip_codes = ['20130', '22602', '99123', '12abc', '39654', '20186']

    # creating the core function
    def get_coords(zip_codes):

    url = f"https://api.zippopotam.us/us/{zip_codes}"


    response = requests.get(url)

    # collecting required information
    if response.status_code == 200:
    data = response.json()
    Places = data['places'][0]

    Longitude = Places['longitude']
    Latitude = Places['latitude']
    City = Places['place name']
    State = Places['state']

    return Longitude, Latitude, City, State
    else:
    return f"Error: {response.status_code},could not retrieve data." # filtering out bad inputs

    # a for loop to check each specific value in the zip_codes tuple
    for codes in zip_codes:
    if len(get_coords(codes)) == 4: # if/else solved error that occured when a zip code was not valid
    print(get_coords(codes)) # a check to make sure the program is running smoothly
    Longitude, Latitude, City, State = get_coords(codes) # unpacks returned tuple from the previous function
    Location = [City, State] # repacks city and state variables into the "Location" tuple
    kml.newpoint (name = codes, description = Location,
    coords = [(Longitude, Latitude)]) # gives the KML file the required data
    else:
    print(get_coords(codes))

    kml.save('GoogleEarth.kml')


    Right now, this block takes zip codes and calls zippotam.us to get location data, then converts that information into a KML file. I just need to reverse it, getting the zip code from the location data.

    Problem is this is for a class, and my teacher has not been good at teaching beginners (a friend helped me write this code). So I haven't tried anything yet due to not really knowing what to do.

    Continue reading...

Compartilhe esta Página