Why can't I access the variable value after a loop

Hi, I use Pluto to run Julia, but I have a problem wanting to get the value of the variable x_t1 out of the loop. Additional, is there a way to use print() and get the value inside the loop in Pluto?

begin
function raiz(x_t, ϵ, n)
	for i=1:n
		x_t1=x_t
		x_t=(x_t+0.2)^0.5
		if abs(x_t1-x_t)<=ϵ
			break
		end
	end
		return x_t1
	end
raiz(0.4, 1.e-10, 100)
end

UndefVarError: x_t1 not defined

Do a search for “local scope” and/or “global scope” inside the Julia manual, e.g. Scope of Variables · The Julia Language

1 Like

Just define x_t1 outside the loop, for instance by assigning x_t1 = 0 before the for.

1 Like

The local keyword introduces a variable name in a scope. If you use it outside the loop, the variable will be available also here. No need to declare to variable global or otherwise.

3 Likes