How to return a global variable from a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jake S
    New Member
    • May 2011
    • 5

    How to return a global variable from a function

    Hello,

    I'm trying to extract coordinates based on the name of imagery files. I created a script to do this using functions:

    Code:
    def lat(dd):
        global lat
        lat_lon = dd.split('_')[1]
        if 'N' in lat_lon:
            lat = int(lat_lon[1:3])
        else:
            lat = int(lat_lon[1:3]) * -1
    
    def lon(dd):
        global lon
        lat_lon = dd.split('_')[1]
        if 'W' in lat_lon:
            lon = int(lat_lon[4:]) * -1
        else:
            lon = int(lat_lon[4:])
    
    list = ['ASTMGTM2_N37W110', 'ASTMGTM2_N45E80']
    for n in list:
        lat(n)
        lon(n)
        print lat, lon
    The script runs correctly for the first value in the list. It returns '37 -110'. However, when it reaches the second value I receive an error:

    TypeError: 'int' object is not callable

    Does anyone know what I am doing wrong? I am new to python and have never really used the 'global' variable before.

    I also tried using the 'return' keyword instead of the global variable:
    Code:
    def lat(dd):
        lat_lon = dd.split('_')[1]
        if 'N' in lat_lon:
            lat = int(lat_lon[1:3])
            return lat
        else:
            lat = int(lat_lon[1:3]) * -1
            return lat
        
    def lon(dd):
        lat_lon = dd.split('_')[1]
        if 'W' in lat_lon:
            lon = int(lat_lon[4:]) * -1
            return lon
        else:
            lon = int(lat_lon[4:])
            return lon
    
    list = ['ASTMGTM2_N37W110', 'ASTMGTM2_N45E80']
    for n in list:
        lat(n)
        lon(n)
        print lat, lon
    This does not error, but I cannot get the numeric values. I receive:

    <function lat at 0x03681F30> <function lon at 0x075A9530>

    I am currently using Python 2.6 and Windows 7 64-bit. Thank you for your help!
    Last edited by Jake S; Nov 16 '11, 01:04 PM. Reason: posted python versions and OS
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Use unique identifiers (names) for your functions and values. In function lat() you can eliminate the assignment to identifier lat.
    Code:
    def lat(dd):
        lat_lon = dd.split('_')[1]
        if 'N' in lat_lon:
            return int(lat_lon[1:3])
        else:
            return int(lat_lon[1:3]) * -1
    Don't use list for a variable name. Built-in Python function list() will be masked.

    Your values can be accessed like this:
    Code:
    seq = ['ASTMGTM2_N37W110', 'ASTMGTM2_N45E80']
    for n in seq:
        v1 = lat(n)
        v2 = lon(n)
        print v1, v2

    Comment

    • Jake S
      New Member
      • May 2011
      • 5

      #3
      Thanks, bvdet! That worked like a charm.

      Comment

      Working...