I'm working on a python code to solve a PDE (Partial Differential Equation) backward in time (i.e. from t = T to t = 0.0). The code is made up of two functions: the first function (def Solve_for_U_values_at_Time_T()) solves a PDE (PDE1) forward in time, and returns an array of values U at a terminal time T (t = 0.0, ..., T). I then want to use this value returned in the first function, in the next function (def Evolve_in_One_Timestep(U)) to solve for a different PDE (PDE2) starting with that value at the terminal time T, going back until I find the value of U at initial time t = 0.0. Note for k in range (M-2, 0,-1): and for n in range(N-1,-1, -1): . See the code below:

def Solve_for_U_values_at_Time_T():
        # M is the number of grid points, N, number of iterations, Dx spatial step and Dt is the time step
        U = zeros(M)
	Block of statements	

	return U

def Evolve_in_One_Timestep(U):

#create an array to store the new values of the solution
	new_U = zeros((M,), float32)

#loop over each gridpoint, except for k= M-1 and k = 0
	for k in range (M-2, 0,-1):
		derivative = -0.25*(U[k+1]**2 - U[k-1]**2)*(Dt/Dx) + 0.5*sqrt(a)*(U[k+1] - 2*U[k] + U[k-1])*(Dt/Dx)
		new_U[k] = U[k] + derivative
#applying boundary conditions 
		new_U[0] = -0.5
		new_U[M-1] = 0
	return  new_U

#initializing the data array

U_Values = Solve_for_U_values_at_Time_T()

for n in range(N-1,-1, -1):
	U_Values = Evolve_in_One_Timestep(U_Values)
	t = n*Dt

Is my idea correct? Any help/advice will be appreciated.

It may be correct or not. It seems that you're solving Burger's equation with a viscosity term, but equations with a laplacian don't easily solve backwards, so there are many questions: is the time T large or small ? What is the first PDE which you're solving in the direct sense ? etc. Also you should plot the solutions to see what your code does.

Also you should not use coloring or other own formats in your text or automatic Python formatting is lost.

Thanks Gribouillis. Sure, these problems (Nonlinear Hyperbolic PDEs) are difficult to solve even in the forward sense due to discontinuities that may develop! It may happen sometimes even if the solution approach is correct, one still gets unusual results! They need special attention!
I've used the PDE that is similar to the one supposed to be solved directly in the position of backward (adjoint - its dual form), as I just want to know if the idea I've tried to explain is correct (I ignored the details of the problem). The terminal time is 0.5 sec, and time steps must be smaller than spatial. Anymore idea is welcome.

@tonyjv, thanks for the advice.