Python is similar to the languages of the "C family", but there are some significant differences and unique properties.
The most obvious syntactic difference between Python and language such as C and ST is that the Python parser recognizes block structures by their indentation. There is no BEGIN/END
or braces {}
to identify the blocks of IF/ELSE
conditions, FOR
and WHILE
loops, or functions.
Comments start with #
and extend to the end of the line. In the first and second line of the source code, you can set a special marker to declare the encoding of the file. We recommend that you use UTF-8 as the encoding if ASCII characters are not required.
For debugging purposes, you use print
for easy output. With the %
operator, you achieve functionality similar to the C function printf()
. The output is displayed in the message view of CODESYS.
Example: print
# encoding:utf-8
# defining a function with the parameter i
def do_something(i):
# if branch
if i>0:
print("The value is: %i" % i)
sum += i
print("The new sum is: %i" % sum)
# else if (optional, there can be none or several elif branches)
elif i=0:
print("The sum did not change: %i" % sum)
# and the final else branch (also optional).
else:
handle_error()
# an endless while loop
while True:
print("I got stuck forever!")
Everything that belongs to the same block has to be indented the same distance. The size of the indentation is irrelevant. Elements such as brackets and braces have a higher priority than indentations. Therefore, the following code segment is completely correct, even if it is written in a "poor programming style":
Example: Indentation
# warning: bad style below. Kids, don't try this at home!
if foo >= bar:
print("foobar")
else:
print(
"barfoo"
)
To avoid ambiguity, you should not mix tabs and spaces in a file.
At this time, mixing tabs and spaces gilt in Python 3 qualifies as a syntax error.
The official Python Style Guide recommends indentation of four spaces and includes some examples of good and poor style. The Python tutorial provides a summary of coding style.
Python is "case-sensitive", similar to C and in contrast to ST. Keywords, such as def
, if
, else
, and while
, have to be lowercase (in contrast to the ST rule: keywords are uppercase). Two identifiers, such as "i" and "I", also identify two different variables.
The following keywords are reserved in Python and not permitted for use as identifiers for variables, functions, etc.: and | as | assert | break | class | continue | def | del | elif | else | except | exec | finally | for | from | global | if | import | in | is | lambda | not | or | pass | print | raise | return | try | while | with | yield
.
Python 3 defined four other keywords: False | None | True | nonlocal
. While the first three are really new, the first three were already predefined constants in Python 2 and should not be used for any other purposes.
For more information, see: Python Style Guide and Python Tutorial