# Question about iterating through a for loop in Julia

Hello. I am new to programming in general.

I am translating some Python into Julia. There is a specific problem that’s been dogging me for like a week. I though it had it down but it’s still causing me troubles.

When I do a for loop in Python, it goes something like this:

``````for i in range(10)
print(i)
``````

And the output will be 0, 1, 2, … ,9

If I try a similar thing in Julia

``````for i = 0:10
print(i)
end

``````

I should be getting 0, 1, 2, … , 10.

So I am working on some code and this is not what seems to be happening.
Specifically, here is the snip of code:

``````    for k = 0:n
println(k)
Phi[k+1,:,:] = F(x0 + cos(pi*(k-1)/n)+1.0)*(x1-x0)/2
end
``````

When I run this code, it only outputs 1,2.

Whatever is going on is making it extremely difficult to get the right results. I’m getting all sorts of bounds errors that I don’t think should be coming up. Is this a bug? Help!

The specific Python code I’m trying to translate is this:

``````  for k in range(n+1):
Phi[k,:,:] = F(x0 + (np.cos(np.pi*k/n) + 1.0)*(x1-x0)/2.0)
``````

Again, I appreciate the help!

EDIT
I restarted my computer and that seemed to fix it for the first time I ran it, but after that it continued to only print 1 and 2.
Restarting Julia/Atom does not seem to fix it.

I see no reason why this should be happening, unfortunately. Are you sure you aren’t getting an error in your code which is causing it to not complete?

Here is an MWE which shows that the for loop does indeed work

``````julia> F(x) = x;

julia> x0 = 0;

julia> x1 = 1;

julia> n = 10;

julia> Phi = zeros(n+1);

julia> for k = 0:n
println(k)
Phi[k+1] = F(x0 + cos(pi*(k-1)/n)+1.0)*(x1-x0)/2
end
0
1
2
3
4
5
6
7
8
9
10``````
2 Likes

I commented absolutely everything else out… and it worked.

Thanks for the debugging tip, hopefully I should be able to wrap it up from here.

EDIT:
There was an error in my argument. Thanks for the help again!

``````for k = 0:n
println(k)
Phi[k+1,:,:] = F(x0 + (cos(pi*k/n)+1.0)*(x1-x0)/2)
println(Phi)
end
``````

EDIT EDIT
OMG its working!