your issue is the missing return statement when rotate is called recursively:
def rotate(d,a):
    if d == 0:
        return a
    #....
    rotate(d-1,b)  # <---- here
if you call rotate(d, a) with d > 0, you enter the recursion rotate(d-1,b)...but you throw away the result and python instead returns None. this is because in python any method call that doesn't explicitly return a value, always returns None...and your initial call to rotate(d, a) with d > 0 never passed by a return statement (only the recursive call with d = 0 does, but you throw away that result)...so it returns None.
this should fix your problem:
def rotate(d,a):
    if d == 0:
        return a
    #....
    return rotate(d-1,b)  # propagate the calculated value back up
see also: Why does my recursive function return None?