The problem is that when a == 0 and we go into the exit condition and must return it to (sum), the program for some reason continues to work and despite the fact that we seem to have had to get out of recursion and return to ( to the sum) we go to the next iteration k + = s (n, n1, a-1,0, k) and after this iteration produces the following error: unsupported operand type (s) for + =: 'int' and 'NoneType' as far as I understand my function is zero here. Also, if n == 2 (the dimension of the matrix is ​​2, then I simply return "None", although when I went to debugger, then (sum) had a certain value Tell me why the output m this error, and how to correct (if possible) Thanks

import random n1 = int(input('matrix(1): ')) n=[[random.randint(-20,40) for r in range(n1)] for s in range(n1)]# cоздаем матрицу def s(n,n1,a,b=0,k=0):#передаем в функцию(матрица, размерность матрицы,индексы элементов, суму) k+=n[a][b]#считаем суму последнего элемента if a == 0:#условия выхода из рекусии return k k +=s(n,n1,a-1,0,k)#сама рекурсия print(s(n,n1,(n1-1)))#начальные агрументы функции(матрица,размерность,значение первого индекса 

    1 answer 1

    First, the exit condition from recursion needs to be checked immediately.
    Secondly, if a != 0 then your function returns None (since there is no explicit return ). From here on the very first iteration (if a >= 2 ) we get:

     k += n[a][b] k += None # Т.к. s(n,n1,a-1,0,k) ничего явно не возвращает, т.е. возвращает None 


    How to fix:
    Run your algorithm on paper, for what you have written is complete nonsense.

    • You say that at the first iteration I will have: "k + = None", but then why, if you go through the program debugger, then "k" takes a value on every pass of the function, besides it sums up correctly?, Maybe I did not understand ? - Oleksiy Koval
    • @OleksiyKoval Call s(n, n1, 2) . k += n[a][b] - approx. a != 0 - do not go into if . k += s(n,n1,1,0,k) - first the call to s(n,n1,1,0,k) . Caught in s(n,n1,1,0,k) . k += n[a][b] - approx. a != 0 - do not go into if . Call s(n,n1,1,0,k) . We fall into s(n,n1,0,0,k) . k += n[a][b] - approx. a == 0 - return (from s(n,n1,0,0,k) ) k (denoted as new_k ). This k returned in k += s(n,n1,1,0,k) , i.e. k += new_k . Further, NOTHING (None) is returned from s(n,n1,1,0,k) to s(n, n1, 2) , i.e. in s(n, n1, 2) : k += None . So we got an error. - Mikhail Murugov
    • Only you had to do it yourself. For example, on paper, as I indicated to you. - Mikhail Murugov
    • the problem is that when I went through the program debugger, I went to the if and return too, but then I got into recursion again, although I read that after the return function cannot continue, so I don’t understand - Oleksiy Koval