Thursday 19 November 2015

LPTHW Exercise 18-21: Functions, Variables, Return

Learn Python the Hard Way by Zed Shaw .: How long will it take for Sebastiaan to pedal his bike to Proxima Centauri?

Code:

import sys
import textwrap

script, origin = sys.argv

name = 'Sebastiaan'
s = 133.78

def cyclist(boost):
    v = '-'
    h = v * (10 + int(boost))
    b = v * (6 + int(boost))
    w = v * (5 + int(boost))
    print textwrap.dedent('''
        {} __@
        {}  _`\<,_
        {}  (*)/ (*)
        ''').format(h, b, w)

def intro():
    cyclist(1)
    print textwrap.dedent('''
        Dutch cyclist {0} Bowier in September 2013 achieved a speed
        of {1} km/h with his VeloX3 bicycle, a new world record for a
        human powered vehicle.

        {0} has now offered you a ride on his bike from {2}
        to a destination of your choice! (Thanks {0}!)
        ''').format(name, s, origin)

def itinerary(destination, distance, time, mode):
    txt = open('travelTimes.txt', 'a+')
    txt.write('\n{}->{} ({} km)\n'.format(origin, destination, distance))
    txt.write('Travel Time: {} hours by {}\n'.format(time, mode))
    txt.seek(0)
    print(txt.read())
    txt.close()

def tripTime(distance, speed):
    return float(distance) / speed

def trip():
    g = raw_input('Where would you like to go? > ')
    d = raw_input('Distance to {} in kilometers? Enter a digit > '.format(g))
    t = tripTime(d, s)
    cyclist(49)
    print textwrap.dedent('''
        Working the pedals at top speed with no breaks, {} would
        get you to {} in {} hours.
        ''').format(name, g, round(t, 2))
    print('Details have been added to your itinerary:')
    itinerary(g, d, round(t, 2), 'bike')

intro()
trip()

Output:

$ python pedalTime.py Toronto

----------- __@
-------  _`\<,_
------  (*)/ (*)


Dutch cyclist Sebastiaan Bowier in September 2013 achieved a speed
of 133.78 km/h with his VeloX3 bicycle, a new world record for a
human powered vehicle.

Sebastiaan has now offered you a ride on his bike from Toronto
to a destination of your choice! (Thanks Sebastiaan!)

Where would you like to go? > Proxima Centauri
Distance to Proxima Centauri in kilometers? Enter a digit > 40142174400000.0

----------------------------------------------------------- __@
-------------------------------------------------------  _`\<,_
------------------------------------------------------  (*)/ (*)


Working the pedals at top speed with no breaks, Sebastiaan would
get you to Proxima Centauri in 3.00061103304e+11 hours.

Details have been added to your itinerary:

Toronto->Detroit (371 km)
Travel Time: 2.77 hours by bike

Toronto->Proxima Centauri (40142174400000.0 km)
Travel Time: 3.00061103304e+11 hours by bike

$