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.
1 Answer 1
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!)
min 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.