Search code examples
pythonidl-programming-language

Loop commands equivalent in IDL to python


Just a quick question regarding converting loop commands in IDL to python.

I have the following loop structure in IDL syntax:

for ... do begin
   for ... do begin
      if ...
         ...
      endif else begin
         ....
      endelse
   endfor
endfor

Now, I would say that is roughly translates to

for ... :
   for ... :
      if ...
         ...
      end if else:
         ....
      endelse
   endfor
endfor

In python.

However, I would say the endelse and endfor commands are redundant? But what should I replace them with?


Solution

  • You are partially right, you just need to abandon the endelse and endfor and replace else if with elif.

    for ... :
       for ... :
          if ...:
             ....
          elif:
             ....
    

    From the Python documentation, here is an example for an If statement:

    >>> x = int(raw_input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...     x = 0
    ...     print 'Negative changed to zero'
    ... elif x == 0:
    ...     print 'Zero'
    ... elif x == 1:
    ...     print 'Single'
    ... else:
    ...     print 'More'
    ...
    More
    

    For statement

    >>> # Measure some strings:
    ... words = ['cat', 'window', 'defenestrate']
    >>> for w in words:
    ...     print w, len(w)
    ...
    cat 3
    window 6
    defenestrate 12