0

I have the following piece of code.

 def num_dim(response_i, m):

   for response_j in response_i['objcontent']:
      if response_i['objkey']== 'explorecube_dimvalues':
         mm = [response_j['title']]
         m.append(mm)

   m=(len(m))
   return m


if __name__=='__main__':

    for response_i in response['response']:
        m=[ ]
        x=0
        def num_dim_2(response_i, m):
           if response_i['objkey']== 'explorecube_dimvalues':
               m = num_dim(response_i, m)
               print(m)
           return m
        num_dimentions= num_dim_2 (response_i, m)
        print(num_dimentions)

The output for print(m) is:

3

but the output for print(num_dimentions) is:

[ ] 
[ ]
3
[ ]

which I expected only 3.

Anyone knows how can I fix this issue (get the value of 3 as the final output). Thank you.

2
  • Why are you creating the function in the for loop? Simply create the function as you did the first and then call upon it when needed. Also we don't know what response['response'] is so its difficult to understand the loop Commented Dec 27, 2016 at 12:34
  • You do understand that you are modifying your function inputs, right? You are modifying the parameter m in your functions (which is a list and so passed-as-reference), and you are also returning it?! It does not make sense. The entire piece of code is gibberish. Commented Dec 27, 2016 at 12:38

1 Answer 1

3

This is because of below piece of code.

def num_dim_2(response_i, m):
           if response_i['objkey']== 'explorecube_dimvalues':
               m = num_dim(response_i, m)
               print(m)
           return m

Even if if condition fails, return m statement is still executed, which will return a blank list.

Further you are executing print(num_dimentions) inside a loop, which means value gets printed as many times as loop is executed. If you need only one output, you will have to print it based on some condition.

Note: its really not good programming practice to use same variable names and also reuse variable names with different type (ex: in num_dim, m is a list and suddenly m is some integer!)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.