0

You know I am a long-time matlab and fortran user. Those languages use explicit end or continue statements to terminate a loop. In Python you must use indentation to identify statements that are in the loop. The example below will not run if I do not put a statement (any statement) at the first indentation level to terminate the inner loop. i.e. if you try to drop down 2 levels of indentation there is an invalid syntax error. So if you comment out the first print statement the error occurs. Is that just the way it is? Is there some kind of dummy continue or enddo statement in Python that can serve as a placeholder for this? I get this error when using python2.7 on Linux. Note using the Spyder Python 3 environment on PC it runs fine with or without the print statement!

from numpy import *
nt=11
nres=2
t=zeros(nt)
y=zeros((nres,nt)) 
for it in range(nt):  
    if it == 0: 
        t[it]=0.
    else:
        t[it]=t[it-1]+1./(nt-1)
    for ir in range(nres):
        y[ir,it]=sin(pi*t[it]+ir*pi/2)
    # need a statement at this level to terminate inner for loop
    print('it=',it,'t=',t[it],'y(:,it)=',y[:,it])
print('end of outer loop')
Big Al
  • 23
  • 3
  • What is the actual error? – Padraic Cunningham Jul 19 '16 at 21:35
  • Your code runs fine in my python (2.7.6 Linux), with or without the inner print statement. – Juan Tomas Jul 19 '16 at 21:40
  • works fine on mine as well (2.7.10 mac). If your after more loop control, maybe take a look at this [doc](https://docs.python.org/3/tutorial/controlflow.html) and the 'break', 'continue' and 'pass' functions – Wokpak Jul 20 '16 at 06:59
  • You know when I import this file it now appears to run in python 2.7.3, when I type the command as >>> from looptest import *. When I just paste the commands into the python window then it gives me an "invalid synrax" error pointing at the skipped indent on the last line. It must just be something to do with the way the commands are terminated. I have a way to make this work, so I apologize for the silly question. I will follow J. Hollom's advice and look into break, continue and pass. Thanks! – Big Al Jul 20 '16 at 14:16
  • 1
    Is this related..? http://stackoverflow.com/questions/7712389/copy-paste-into-python-interactive-interpreter-and-indentation – roygvib Jul 20 '16 at 15:45

0 Answers0