Sherman Sze Sherman Sze - 1 year ago 78
Python Question

If-statement seemingly ignored by Write operation

What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added.
Note that I also have a list Coordinates that stores the same information. The list works as no repeats are added.(By checking) However, the text file has the same coordinates appended over and over again even though it theoretically shouldn't as it is contained within the same if-block as the list.

import requests

pokemon_url = ''

while True:
response = requests.get(pokemon_url)

pokemon = response.json()[0:]

Sighting = 0
Coordinates = [None] * 100

for num in range(len(pokemon)):
if pokemon[num]['pokemon_name'] == 'Aerodactyl':
Lat = pokemon[num]['latitude']
Long = pokemon[num]['longitude']
if (Lat, Long) not in Coordinates:
Coordinates[Sighting] = (Lat, Long)
file = open("aerodactyl.txt", "a")
file.write(str(Lat) + "," + str(Long) + "\n")
Sighting += 1

For clarity purposes, this is the output
For clarity purposes, this is the output

Answer Source

You need to put your Sighting and Coordinates variables outside of the while loop if you do not want them to reset on every iteration.

However, there are a lot more things wrong with the code. Without trying it, here's what I spot:

  1. You have no exit condition for the while loop. Please don't do this to the poor website. You'll essentially be spamming requests.
  2. file.close should be file.close(), but overall you should only need to open the file once, not on every single iteration of the loop. Open it once, and close once you're done (assuming you will add an exit condition).
  3. Slicing from 0 (response.json()[0:]) is unnecessary. By default the list starts at index 0. This may be a convoluted way to get a new list, but that seems unnecessary here.
  4. Coordinates should not be a hard-coded list of 100 Nones. Just use a set to track existing coordinates.
  5. Get rid of Sighting altogether. It doesn't make sense if you're re-issuing the request over and over again. If you want to iterate through the pokémon from one response, use enumerate if you need the index.
  6. It's generally good practice to use snake case for Python variables.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download