Python 控制结构(附示例)
循环
与 C 和 ST 相比, for Python 中的循环不计算循环变量,而是遍历一个序列。这种序列可以是“字典”、列表、元组、字符串中的字符或文件中的行。
下面的例子展示了一些 for 循环:
from __future__ import print_function
print("Enumerating over a simple list:")
for i in (1,2,3,4):
print(i, end=", ") # end= replaces the newline with ", "
print() # but we still need a newline at the end of this case.
print("Enumerating over the characters in a string:")
for i in "CODESYS": # characters are representet as strings of length 1.
print(i, end=", ")
print()
print("Enumerating over the integers 1 to 4:")
for i in range(1, 5): # upper bound is exclusive.
print(i, end=", ")
print()
print("Enumerating using xrange:")
for i in xrange(5): # xrange is similar to range, but needs less memory for large ranges.
print(i, end=", ")
print()
print("Enumerating including the item number:")
for i, v in enumerate("CODESYS"):
print(i, v)结果输出:

如果您需要除项目之外的索引或编号,那么您应该使用 enumerate 如示例脚本的最后一种情况所示。以下代码被认为是不良风格:
text = "CODESYS"
for i in range(len(text)): # BAD STYLE!
v = text[i] # DON'T TRY THIS AT HOME!
print(i, v)除了 for 循环,Python 也有 while 与 C 和 ST 中的循环非常相似的循环:
i = 0
while i < 3;
print(i)
i += 1注意:这个例子不是很实用。您更有可能使用 for 带范围的循环。
如果别的
这 if/else 构造类似于其他编程语言中的构造。这是一个简短的例子:
from __future__ import print_function
i = int(system.ui.query_string("Please enter an integral number..."))
if i < 0:
print("Your number was negative.")
elif i > 0:
print("Your numer was positive.")
else:
print("It seems your number was zero.")这 else 分支是可选的,可以有零个、一个或多个 elif 分支机构。
函数、类和方法
Python 允许使用方法定义函数和类。具有方法的类基本上类似于 ST 中的功能块,或 C++、Java 或 C# 等语言中的类。但是,Python 不支持接口。
有关详细信息,请参阅 Python 文档以定义 职能 和 课程.
#defining a function with name sum and two parameters a and b:
def sum(a, b):
return a + b # we return the sum of a and b.
# we can now call the function defined above:
print(sum(5,7))
# Now we define a class Foo:
class Foo:
# The class gets a method "bar".
# Note: for methods, the first parameter is always "self" and
# points to the current instance. This is similar to "this" in
# ST and other languages.
def bar(self, a, b):
print("bar(%s,%s)" % (a,b))
# We create an instance of the class:
f = Foo()
# We call the method bar on the instance.
f.bar("some", "params")模块和标准库
在 IEC 中,您可以导入库以供其他编写的代码重用。作为一个挂件,在 Python 中有导入模块的可能性。
这 Python 标准库 包含许多用于不同目的的模块,例如:
字符串处理
日期和时间处理
收藏品
穿线
数学函数
文件处理
持久性
压缩和归档
数据库访问
加密服务
网络和互联网访问
发送电子邮件
要创建您自己的模块,请编写一个 Python 文件来定义您要提供的函数和类。将此文件保存到与我们的示例脚本相同的目录中。如果你命名文件 mymodule.py, 然后你可以用 import mymodule.
下面是导入和使用余弦函数和 pi 常数的示例 math 模块:
from math import cos, pi print(pi) # prints 3.14159265359 print(cos(pi)) # prints -1.0
以下包含访问有关操作系统、Python 版本和解释器信息的更多示例:
import os print(os.environ["OS"]) from sys import platform, version, executable print(platform) print(version) print(executable)

有一个特殊的模块 __future__ 用于激活新的语言功能。最重要的是,它在 Python 开发人员引入向后兼容的新功能时使用。这些功能必须用特殊的“__future__ 进口”。我们在大多数示例脚本中使用的一个示例是激活新的幂语法 print 作为函数而不是语句。
# make print() a function instead of a statement from __future__ import print_function
Python 文档提供了完整的 所有的清单 __future__ 进口.
除了普通的 Python 模块,IronPython 代码还可以访问 .NET 程序集,就好像它们是 Python 模块一样。这将打开访问 .NET 框架类库 和第三方库。下面是一个示例,如何通过 Windows Forms 图书馆:
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello")