Converting decimal degrees to deg, min, sec

Question

Write a program to convert an longitude or latitude expressed as a signed quantity in degrees (possibly with a fractional component expressed in decimal notation) to one expressed in degrees, minutes and seconds (the first two as integers and the last as a floating point number). Input latitudes may be $-90 - +90$ and longitudes $-180 - +180$.

In addition to the numerical values of degrees, minutes and seconds, also output a string in the form deg° min′ sec″ X where X is N, S, E, or W as appropriate. For example,

In [x]: deg_to_dms(38.889469)
Out[x]: (38, 53, 22.088400000007823)

In [x]: deg_to_dms(38.889469, pretty_print='latitude')
Out[x]: '38° 53′ 22.0884″ N'

In [x]: deg_to_dms(-77.035258)
Out[x]: (-77, 2, 6.928799999994226)

In [x]: deg_to_dms(-77.035258, pretty_print='longitude')
Out[x]: '77° 2′ 6.9288″ W'

Solution

To access solutions, please obtain an access code from Cambridge University Press at the Lecturer Resources page for my book (registration required) and then sign up to scipython.com providing this code.