logo

Python 3 Programming Assignments

   

Added on  2023-03-16

26 Pages6985 Words50 Views
Python 3
Submitted by:
Date:
Python 3 Programming Assignments_1
Table of content
Introduction
Single program which comprises the various tasks (1.1-1.10)
LO1 Define basic algorithms to carry out an operation and outline the process of programming
an application.
LO2 Explain the characteristics of procedural, object-orientated and event driven programming,
conduct an analysis of a suitable Integrated Development Environment (IDE)
LO3 Implement basic algorithms in code using an IDE
LO4 Determine the debugging process and explain the importance of a coding standard
Conclusion
Reference
Python 3 Programming Assignments_2
1.1 Hello C# (Menu Item 1)
import time
name = input('Enter your name: ')
time = input('Enter time of the day: ')
print('Hello, world!')
currentTime = time.strftime('%H:%M')
if currentTime.hour < 12 :
print('Good morning')
if currentTime.hour > 12 :
print('Good afternoon')
if currentTime.hour > 6 :
print('Good evening')
1.2 Your Name Characters (Menu item 2)
for i in range(0, 5):
for j in range(0, i+1):
print("0",end="")
print()
1.3 The Area and the perimeter of a Rectangle (Menu item 3)
print("Enter 'x' for exit.");
side1 = input("Enter length of first side: ");
if side1 == 'x':
exit();
else:
side2 = input("Enter length of second side: ");
side3 = input("Enter length of third side: ");
a = float(side1);
b = float(side2);
c = float(side3);
s = (a + b + c)/2;
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5;
print("\nArea of Triangle = %0.2f" %area);
Python 3 Programming Assignments_3
1.4 Time of Journey (Menu item 4)
import simplejson, urllib
import re
import time
import operator
import os
import sys
import argparse
from collections import defaultdict
REMOVE_HTML_TAGS = r'<[^>]+>'
GEOCODE_BASE_URL =
'http://maps.googleapis.com/maps/api/geocode/json'
DIRECTIONS_BASE_URL =
'http://maps.googleapis.com/maps/api/directions/json'
def geocode(address, **geo_args):
geo_args.update({
'address': address
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def reverse_geocode(lat, lng):
geo_args = {
'latlng': "%s,%s" % (lat, lng)
}
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def directions(source, destination, **geo_args):
geo_args.update({
'origin': source,
'destination': destination
})
Python 3 Programming Assignments_4
url = DIRECTIONS_BASE_URL + '?' + urllib.urlencode(geo_args)
return simplejson.load(urllib.urlopen(url))
def output_routes(mode, routes):
timings = defaultdict(lambda: 0)
distances = defaultdict(lambda: 0)
for route in routes:
for leg in route['legs']:
print "Distance: ", leg['distance']['text']
print "Duration: ", leg['duration']['text']
for step in leg['steps']:
travel_mode = step['travel_mode']
if 'html_instructions' in step:
direction_text = re.sub(REMOVE_HTML_TAGS, '
', step['html_instructions'])
else:
direction_text = '(no direction text)'
distance = step['distance']
duration = step['duration']
encoded_direction_text =
direction_text.encode('latin1', errors='ignore')
print "%s (%s, %s, %s)" %
(encoded_direction_text, travel_mode,
duration['text'], distance['text'])
timings["%s-%s" % (mode, travel_mode)] +=
duration['value']
distances["%s-%s" % (mode, travel_mode)] +=
distance['value']
return timings, distances
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("--dry-run", required=False, default=False,
action='store_true', help="Don't make API calls")
ap.add_argument("--min-lng", required=False, default=103.73,
type=float, help="Minimum longitude (Default 103.73)")
ap.add_argument("--max-lng", required=False, default=103.84,
type=float, help="Maximum longitude (Default 103.84)")
ap.add_argument("--min-lat", required=False, default=1.27,
type=float, help="Minimum latitude (Default 1.27)")
ap.add_argument("--max-lat", required=False, default=1.345,
type=float, help="Maximum latitude (Default 1.345)")
Python 3 Programming Assignments_5
ap.add_argument("--step-lng", required=False,
default=0.00125,
type=float, help="Increment longitude amount (Default
0.00125)")
ap.add_argument("--step-lat", required=False,
default=0.00125,
type=float, help="Increment latitude amount (Default
0.00125)")
args = vars(ap.parse_args())
print args
# load existing timings
if os.path.exists('timings.csv'):
timings = [ row.strip().split('\t') for row in
file('timings.csv') ]
else:
timings = []
print 'Found %d existing timings' % len(timings)
latlngs = dict(('%s,%s' % (k,v), True) for (k,v,_,_,_,_) in
timings)
if not args['dry_run']:
results = geocode(address="The Pinnacle @ Duxton")
data = results[0]
location = data['geometry']['location']
lat, lng = location['lat'], location['lng']
source = "%s,%s" % (lat, lng)
print source
with open('source.txt', 'w') as sourcef:
sourcef.write("%s,%s\n" % (lat, lng))
results = reverse_geocode(lat, lng)
print 'Reverse geocoded address for lat,lng: %.3f,%.3f' %
(lat, lng)
print '\n'.join([ x['formatted_address'] for x in results
])
print
time.sleep(5)
eight_am =
int(time.mktime(time.struct_time([2014,7,14,8,0,0,0,0,0])))
# starting longitude
Python 3 Programming Assignments_6

End of preview

Want to access all the pages? Upload your documents or become a member.

Related Documents
LO1 Define basic Algorithms to Carry Out an Operation
|24
|6156
|124