#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    25
    Rep Power
    0

    Returning a value from a function


    I'm finally starting to turn some of my code into functions so I don't have to write a new program every time I get a new data file to process. At the end of the function I am trying to return two values. I want one of the values to be flux_'a number' where 'a_number' increases by one starting at one each time I run the function in a file. In this particular instance I will call the function four times so I hope to end up with flux_1, flux_2 etc. I am trying to do this at lines 44 and 45 of the code but I get a "SyntaxError: can't assign to function cell" error. Any insight is appreciated.

    Code:
    #import numpy as np
    import matplotlib.pyplot as plt
    
    flux = []
        
    SEM = []
    
    depth = []
    
    c = 1
    
    def data_reader(file_name, first_surface):
        
        del flux[:]
        
        del SEM[:]
        
        del depth[:]
        
        with open (file_name) as inf:
        
            lines = inf.readlines()
    
            for (i, line,) in enumerate(lines):
        
                if ' surface  %d' %first_surface in line:
        
                    data = (lines[i+1].strip())
                    
                    fields = data.split()
        
                    numbers = list(map(float,fields))   
        
                    flux.append(numbers[0])
    
                    SEM.append(numbers[1])
    
                    first_surface += 1
    
                    depth.append(first_surface - 101)                
    
    
        str('flux_%d'  %c) = flux         
        return ('flux_%d', SEM, first_surface) %c
        c=+1
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    157
    Rep Power
    2
    First of all, you shouldn't have any code after the "return"
    Then you should have all the variables in a tuple that get's mod'd to the format. For example:
    >>> for i in xrange(3):
    ... print "flux_%d %s" %(i, "abc")
    ...
    flux_0 abc
    flux_1 abc
    flux_2 abc

    where the return takes the place of print in this example.
    note that in Python 2.7 the format specifier notation (with format dictionaries, {0:d}) is preferred over "modular convolution" (i.e., "%") string formatting.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    25
    Rep Power
    0
    Originally Posted by rrashkin
    First of all, you shouldn't have any code after the "return"
    Then you should have all the variables in a tuple that get's mod'd to the format. For example:
    >>> for i in xrange(3):
    ... print "flux_%d %s" %(i, "abc")
    ...
    flux_0 abc
    flux_1 abc
    flux_2 abc

    where the return takes the place of print in this example.
    note that in Python 2.7 the format specifier notation (with format dictionaries, {0:d}) is preferred over "modular convolution" (i.e., "%") string formatting.
    I moved everything to before the return statement. I basically understand what you are saying to do. Let me explain the problem I am having and why I tried to resolve it that way so you might be better able to help me.

    The four flux values I am trying to graph against the first surface value on the same graph. The problem is that the program appears to overwrite flux_1-3 with all of the values of flux_4 so I get four lines of different colors all over top of each other. I know that the data is different because I have it being plotted on separate plots where one can clearly see that the lines are different. I attempted to return unique flux values each time the function runs but obviously without success. I have included the original program so maybe someone can tell if I am just calling my function improperly which causes it to overwrite values.

    Code:
    #import numpy as np
    import matplotlib.pyplot as plt
    
    flux = []
        
    SEM = []
    
    depth = []
    
    c = 0
    
    def data_reader(file_name, first_surface):
    
        del flux[:]
        
        del SEM[:]
        
        del depth[:]
        
        with open (file_name) as inf:
        
            lines = inf.readlines()
    
            for (i, line,) in enumerate(lines):
        
                if ' surface  %d' %first_surface in line:
        
                    data = (lines[i+1].strip())
                    
                    fields = data.split()
        
                    numbers = list(map(float,fields))   
        
                    flux.append(numbers[0])
    
                    SEM.append(numbers[1])
    
                    first_surface += 1
    
                    depth.append(first_surface - 101)                
    
    
                    
        return (flux, SEM, first_surface)
                    
    data1 = data_reader('concrete_40billion.txt', 101)
    flux_1 = data1[0]
    SEM_1 = data1[1]
    
    plt.figure(1)
    plt.rcParams['legend.loc'] = 'best'
    plt.autoscale(enable=True, axis='y', tight=None)
    plt.autoscale(enable=True, axis='x', tight=None)
    plt.plot(depth, flux_1, 'k')
    plt.loglog()
    print('plots created')
    plt.show()
    
    data2 = data_reader('du_1m_20billion.txt', 101)
    flux_2 = data2[0]
    SEM_2 = data2[1]
    
    plt.figure(2)
    plt.rcParams['legend.loc'] = 'best'
    plt.autoscale(enable=True, axis='y', tight=None)
    plt.autoscale(enable=True, axis='x', tight=None)
    plt.plot(depth, flux_2, 'k')
    plt.loglog()
    print('plots created')
    plt.show()
    
    data3 = data_reader('du_2m_20billion.txt', 101)
    flux_3 = data3[0]
    SEM_3 = data3[1]
    
    plt.figure(3)
    plt.rcParams['legend.loc'] = 'best'
    plt.autoscale(enable=True, axis='y', tight=None)
    plt.autoscale(enable=True, axis='x', tight=None)
    plt.plot(depth, flux_3, 'k')
    plt.loglog()
    print('plots created')
    plt.show()
    
    data4 = data_reader('du_3cm_20billion.txt', 101)
    flux_4 = data4[0]
    SEM_4 = data4[1]
    
    plt.figure(4)
    plt.rcParams['legend.loc'] = 'best'
    plt.autoscale(enable=True, axis='y', tight=None)
    plt.autoscale(enable=True, axis='x', tight=None)
    plt.plot(depth, flux_4, 'k')
    plt.loglog()
    print('plots created')
    plt.show()
    
    #difference = [a - b for a,b in zip(flux_1, flux_2)]
    #print difference
    
    plt.rcParams['legend.loc'] = 'best'
    plt.figure(5)
    #plt.xlim(0, 0.04)
    #plt.ylim(0, 7000)
    plt.autoscale(enable=True, axis='y', tight=None)
    plt.autoscale(enable=True, axis='x', tight=None)
    plt.plot(depth, flux_1, 'k',label='flux 1')
    plt.hold(True)
    plt.plot(depth, flux_2, 'g', label='flux 2')
    plt.hold(True)
    plt.plot(depth, flux_3, 'b', label='flux 3')
    plt.hold(True)
    plt.plot(depth, flux_4, 'r', label='flux 4')
    plt.hold(True)
    plt.xlabel('Depth (cm)')
    plt.ylabel('Flux (particles/cm^2*s)')
    plt.loglog()
    plt.legend()
    print('plots created')
    plt.show()

IMN logo majestic logo threadwatch logo seochat tools logo