Python Control Structures (with Examples)
Loops
As opposed to C and ST, for
loops in Python do not count loop variables, but iterate over a sequence. This kind of sequence can be a "dictionary", a list, a tuple, the characters in a string, or lines in a file.
The following example shows some for
loops:
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)
Resulting output:

If you require an index or number in addition to the item, then you should use enumerate
as shown in the last case of the sample script. The following code is considered as poor style:
text = "CODESYS" for i in range(len(text)): # BAD STYLE! v = text[i] # DON'T TRY THIS AT HOME! print(i, v)
Besides for
loops, Python also has while
loops which are very similar to those in C and ST:
i = 0 while i < 3; print(i) i += 1
Note: This example is not very practical. You would more likely use a for
loop with a range.
IF / ELSE
The if/else
construct is similar to those in other programming languages. Here is a short example:
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.")
The else
branch is optional and there can be zero, one, or many elif
branches.
Functions, classes, and methods
Python allows for defining functions and classes with methods. A class with methods is basically similar to a function block in ST, or classes in languages such as C++, Java, or C#. However, Python does not support interfaces.
For detailed information, see the Python documentation for defining Functions and Classes.
#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")
Modules and standard libraries
In IEC, you can import libraries for reuse by other written code. As a pendant, there is the possibility in Python of importing modules.
The Python standard library contains many modules for different purposes, such as:
String processing
Date and time handling
Collections
Threading
Mathematical functions
File handling
Persistence
Compression and archiving
Database access
Encryption services
Network and Internet access
Sending of emails
To create your own modules, write a Python file that defines the functions and classes that you want to provide. Save this file to the same directory as our sample script. If you name the file mymodule.py
, then you can import it with import mymodule
.
Here is an example of importing and using the cosine function and the pi constant from the math
module:
from math import cos, pi print(pi) # prints 3.14159265359 print(cos(pi)) # prints -1.0
The following contains more examples that access information about the operating system, the Python version, and the interpreter:
import os print(os.environ["OS"]) from sys import platform, version, executable print(platform) print(version) print(executable)

There is a special module __future__
for activating new language features. Above all, it is used when Python developers introduce new functionalities that are backward compatible. These kinds of functionalities have to be activated with special "__future__
imports". One example that we use in most of our sample scripts here is the activation of the new power syntax of print
as a function instead of a statement.
# make print() a function instead of a statement from __future__ import print_function
The Python documentation provides a complete list of all __future__
imports.
In addition to the normal Python modules, IronPython code can also access .NET assemblies as if they were Python modules. This opens the access to the .NET framework class library and third-party libraries. Here is an example how to open a dialog by means of the Windows Forms
library:
import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox MessageBox.Show("Hello")