Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function to take a string as input in Python 3

I am trying to create a simple latitude/longitude converter (from degrees/minutes/seconds to decimal degrees), but I am having an issue with how the function solicits and processes user input, namely with respect to the cardinal direction of the latitude (N/S) or longitude (E/W). I would like the function to take a user input of N/S/E/W and apply a conditional statement to ensure the conversion output is positive (N or E) or negative (S or W).

I am trying to make the user interface as user-friendly as possible, so that the layman will not have to enter the string letter using quotation marks.

Here is the code so far:

def coord_convert (card,deg,mins,sec):
    if card == 'S' or card == 's' or card == 'W' or card == 'w':
        deg=-deg
        mins=-mins
        sec=-sec
    mins_decimal = mins + (float(sec)/60)
    deg_decimal = deg + (mins_decimal/60)
    return deg_decimal

If the user calls the function coord_convert(W,30,30,0) this will generate an error, while coord_convert('W',30,30,0) returns the correct -30.5. Is there any way to make this user-friendly such that the card input is correctly read in as a string?

By the way, this function was converted from Python 2.7 to Python 3.6 so any other errors or pointers (especially dealing with the integer and float handling) would be appreciated.

like image 827
uscav8r Avatar asked Sep 10 '26 01:09

uscav8r


1 Answers

As long as you document this properly, the requirement that a user pass a string to the function input should not cause concern or issues. This is standard in all Python functions that accept a string input.

Of course, if you have some other way for users to enter information than interfacing with your function directly (i.e. via command line arguments), then you shouldn't need quotes around the string that the user provides. But that will require more code, and won't change this function.

The same applies if the user has the string stored in a variable:

cardinal = 'W'
coord_convert(cardinal, 30, 20, 10)

What I would recommend is making sure you build in Python 2 compatibility (with from __future__ import division) and add a function docstring. You can also simplify your check for cardinality.

from __future__ import division

def coord_convert(cardinal, deg, mins, sec):
    '''
    This is your function docstring.
    Put some examples here, along with expected inputs and output.
    '''
    if cardinal.upper() in ['S', 'W']:
        deg = -deg
        mins = -mins
        sec = -sec
    mins_decimal = mins + (float(sec)/60)
    deg_decimal = deg + (mins_decimal/60)
    return deg_decimal
like image 180
Andrew Guy Avatar answered Sep 12 '26 16:09

Andrew Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!