Posts

Showing posts from July, 2018

Short hands of loops and conditions

#shorthand.py result = [] for x in [1,2,3]:     for y in [3,1,4]:         if x != y:             result.append((x, y)) print(result) result=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] print(result) Output [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Python Programs

# Fibonacci series # Using Multiple assignments and keyword argument end # the sum of two elements defines the next a, b = 0, 1 while a < 10:     print(a, end=' ')     a, b = b, a+b

Calling Google Geocoding Web Service

import urllib.request, urllib.parse, urllib.error import json # Note that Google is increasingly requiring keys for this API serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' address = input('Enter location: ') if len(address)>0:     url = serviceurl + urllib.parse.urlencode(         {'address': address})     print('Retrieving', url)     uh = urllib.request.urlopen(url)     data = uh.read().decode()     print('Retrieved', len(data), 'characters')     try:         js = json.loads(data)     except:         js = None     if not js or 'status' not in js or js['status'] != 'OK':         print('==== Failure To Retrieve ====')         print(data)     print(json.dumps(js, indent=4))     lat = js["results"][0]["geometry"]["location"]["lat"]    ...

Parsing XML files using Python

Python provides xml,tree.ElementTree module to part the elements in XML Example 1 import xml.etree.ElementTree as ET data = ''' <person>   <name>Amit</name>   <phone type="mobile">+91 98108 49501</phone> </person>''' tree = ET.fromstring(data) print('Name:', tree.find('name').text) print('Name:', tree.find('phone').text) print('Attr:', tree.find('phone').get('type')) Output Name: Amit Name: +91 98108 49501 Attr: mobile Example 2 import xml.etree.ElementTree as ET input = ''' <stuff>     <users>         <user x="2">             <id>001</id>             <name>Rajesh</name>         </user>         <user x="7">             <id>A009</id>             <nam...