If and else statement in Google Places API script in Python
<p>I am attempting to write a script that will loop through list items and query the google places api. </p>

<p>The problem is that some of the queries will return no results, while other queries will.</p>

<p>The query results are gathered into lists. For every query that returns no results I would like to insert 'no results' string into list.</p>

<p>This is the script I have so far (API Key is fake):</p>

<pre><code>companies = ['company A', 'company B', 'company C']    

#create list items to store API search results
google_name = []
place_id = []
formatted_address = []



#function to find company id and address from company names
def places_api_id():
    api_key = 'AIzaSyAKCp1kN0cHvO7t_NlqMagergrghhehtsrht'
    url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
    #replace spaces within list items with %20
    company_replaced = company.replace(' ', '%20')
    final_url = url + '?query=' + company_replaced +'&amp;key=' + api_key
    json_obj = urllib2.urlopen(final_url)
    data = json.loads(json_obj)

    #if no results, insert 'no results'
    if data['status'] == 'ZERO RESULTS':
        google_name.append('no results')
        place_id.append('no results')
        formatted_address('no results')

    #otherwise, insert the result into list
    else:
        for item in data['results']:
            google_name.append(item['name'])
            place_id.append(item['place_id'])
            formatted_address.append(item['formatted_address'])

#run the script
for company in companies:
    places_api_id()
</code></pre>

<p>Unfortunately when I run the script python produces the following error:</p>

<pre><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-159-eadf5f84e27f&gt; in &lt;module&gt;()
      1 for company in companies:
----&gt; 2     places_api_id()
      3 

&lt;ipython-input-153-f0e25b871a0e&gt; in places_api_id()
      6         final_url = url + '?query=' + company_replaced +'&amp;key=' +     api_key
      7         json_obj = urllib2.urlopen(final_url)
----&gt; 8         data = json.loads(json_obj)
  9         if data['status'] == 'ZERO RESULTS':
 10                 google_name.append('no results')

/usr/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook,     parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not     kw):
--&gt; 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

/usr/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
    364 
    365         """
--&gt; 366         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    367         end = _w(s, end).end()
    368         if end != len(s):

`TypeError: expected string or buffer
</code></pre>

<p>I would really appreciate your help and advice on how to get this script working, I've been staring at it for hours.</p>

<p>Thank you
Kamil</p>

<p>UPDATE</p>

<p>I am now loooping the following list through the script:</p>

<pre><code>companies = ['MARINE AND GENERAL MUTUAL LIFE ASSURANCE SOCIETY',
 'KENTSTONE PROPERTIES LIMITED',
 'ASHFORD CATTLE MARKET COMPANY LIMITED(THE)',
 'ORIENTAL GAS COMPANY, LIMITED(THE)',
 'BRITISH INDIA STEAM NAVIGATION COMPANY LIMITED',
 'N &amp; C BUILDING PRODUCTS LIMITED',
 'UNION MARINE AND GENERAL INSURANCE COMPANY LIMITED,(THE)',
 '00000258 LIMITED',
 'METHODIST NEWSPAPER COMPANY LIMITED',
 'LONDON AND SUBURBAN LAND AND BUILDING COMPANY LIMITED(THE)']
</code></pre>

<p>after I run the script this is what Google Places API returns in the google name list:</p>

<pre><code>[u'The Ashford Cattle Market Co Ltd',
 u'Orient Express Hotels',
 u'British-India Steam-Navigation Co Ltd',
 u'N-Of-One, Inc.',
 u'In-N-Out Burger',
 u'In-N-Out Burger Distribution Center',
 u"Wet 'n Wild Orlando",
 u'In-N-Out Burger',
 u'Alt-N Technologies (MDaemon)',
 u'Model N Inc',
 u"Pies 'n' Thighs",
 u"Bethany Women's Center",
 u"Jim 'N Nick's Bar-B-Q",
 u"Steak 'n Shake",
 u'New Orleans Ernest N. Morial Convention Center',
 u"Jim 'N Nick's Bar-B-Q",
 u"Jim 'N Nick's Bar-B-Q",
 u"Jim 'N Nick's Bar-B-Q",
 u'Theatre N at Nemours',
 u'Model N',
 u"Jim 'N Nick's Bar-B-Q",
 u'Memphis Rock n Soul Museum',
 u"Eat'n Park - Squirrel Hill",
 u'Travelers',
 u'American General Life Insurance Co',
 u'258 Ltd Rd',
 u'The Limited',
 u'258, New IPCL Rd',
 u'London Metropolitan Archives',
 u'Hampstead Garden Suburb Trust Ltd']
</code></pre>

<p>Majority of the company names returned by Google are not even  on the companies list and also there are many more of them. I am really confused now.</p>