Search code examples
pythonfor-loopif-statementindentation

Only first value in function with multiple nested loops


I'm quite new to Python and I'm running into a very basic problem. I've written a function with multiple for loops and an if statement. This code when run separately shows all values that I expect. However when put it into a def function it returns only the first value. I know it has something to do with indentation and using yield instead of return in the function. However trying to resolve it with both options still gives one result back. Below is the sample of the code:

def generate_body(objectFr, properties):
objFrame = objectFr
data = properties

for obj in objFrame.Object_Naam:
    properties = data.loc[data['Objects'] == obj, 'attribuut_naam'].dropna()
    # minOccur = data.loc[data['Objects'] == obj, 'minOccurs'].dropna()
    
    for prop in properties:
        last = properties.iloc[-1]
        first = properties.iloc[0]
        jsonbody = []
        # bodystring = ''.join(jsonbody)
        if prop == first:
            jsonbody.append('"' + obj + '",' + ' "type": "object,"' + ' "properties": {' + str(prop) + '"' + ': { "type": "string" }' )
        elif prop == last:
            jsonbody.append('"' + str(prop) + '"' + ': { "type": "string" }' )
        else:
            jsonbody.append('"' + str(prop) + '"' + ': { "type": "string" },' )
        
    return ''.join(jsonbody)

Can someone please help me out?


Solution

  • Three things:
    The indentation under the def is out of place.
    The return statement must be out of the for loop.
    Put the jsonbody[] in the right place.

    Try this:

    def generate_body(objectFr, properties):
        objFrame = objectFr
        data = properties
        jsonbody = []
    
        for obj in objFrame.Object_Naam:
            properties = data.loc[data['Objects'] == obj, 'attribuut_naam'].dropna()
            # minOccur = data.loc[data['Objects'] == obj, 'minOccurs'].dropna()
        
            for prop in properties:
                last = properties.iloc[-1]
                first = properties.iloc[0]
                
                # bodystring = ''.join(jsonbody)
                if prop == first:
                    jsonbody.append('"' + obj + '",' + ' "type": "object,"' + ' "properties": {' + str(prop) + '"' + ': { "type": "string" }' )
                elif prop == last:
                    jsonbody.append('"' + str(prop) + '"' + ': { "type": "string" }' )
                else:
                    jsonbody.append('"' + str(prop) + '"' + ': { "type": "string" },' )
            
        return ''.join(jsonbody)