在 IDL 中相当于 python 的循环命令

Loop commands equivalent in IDL to python

关于将 IDL 中的循环命令转换为 python 的简单问题。

我在 IDL 语法中有以下循环结构:

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

现在,我想说的是大致翻译成

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

在python.

但是,我会说 endelse 和 endfor 命令是多余的?但是我应该用什么来代替它们呢?

python 中没有 endif 或 endfor。您取消缩进以表明 elif 是 "else if"

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

我可能将 "end if begin" 误解为一个新的 if 语句,而不是简单的 else。在那种情况下,它是

 for ... :
   for ... :
      if ...:
         ...
      else:
         ... 

你说对了一部分,你只需要放弃 endelseendfor 并将 else if 替换为 elif

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

来自 Python documentation,这是一个 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

Python 分组仅依赖于缩进,因此您的 iffor 循环/分组不需要 end

这是有效的Python代码:

for i in range(5):
    print(i)

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

你不用任何东西代替它们。

来自the Python tutorial

The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

要结束一个块,只需return到上一级缩进即可。