Basic Syntax of Python (with Examples)

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.

Note

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 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.

Variables and data types

Python is a powerful, dynamically typed language – all type information is evaluated at runtime. Variables hold references to objects, and the object knows its type, not the variable. When a programmer attempts to execute an operation that is not possible (for example, adding an integer and a string), Python throws an exception at runtime.

Consequently, there are no declarations of variables and their types. In Python, variables are created only to assign values to them. This is completely different in C and ST where types are strong and static. Every variable is declared with a type, and at compile time the compiler checks that the type and operators are permitted.

Refer to the following examples for dealing with variables:

Example: Variables

# assign the integer 1 to the variable i (also "creates" the variable")
i = 1

# assign the string "foobar" to the variable s
s = "foobar"

# Add 5 to the integer i - this is equivalent to i = i + 5
i += 5
# i now holds the integer 6.

# Try to add i and s - this will throw an exception when executed
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
result = i + s

# variables can also be "undeclared" by deleting them.
# Further access to the variable i will throw a NameError exception,
# as the variable does not exist any more.
del i

i += 5 # now throws an exception: NameError: name 'i' is not defined

All existing variables reference one value only. There is not any unassigned or uninitialized variables in Python. To express the absence of a value, Python provides a special object: None. In C or ST, you would use a null pointer. Its only purpose is to express “no value here”, although None is actually an existing instance of the class NoneType.

Numeric types and floating points

In contrast to the dozens of integer types in IEC or C, there is only one integer type in Python. Integer types in Python do not have a fixed size. Instead, they grow as needed and are limited only by available memory.

Example: Integers.py

from __future__ import print_function

i = 1
print(i)

j = 0x1234   # hex number, is 16#1234 in IEC and 4660 in decimal
k = 0o123    # octal number, is 8#123 in IEC and 83 decimal
l = 0b101010 # binary number, is 2#101010 in IEC and 42 in decimal
print(j, k, l)

m = (2 + 3)*10 # k is 50 now
print(m)

n = 10 ** 100 # 10 to the power of 100
print(n)

Resulting output:

There is also only one floating-point type in Python which is similar to the IEC data type LREAL. It provides 64-bit IEEE floating point arithmetic.

The syntax is like C-based languages for the most part:

Example: Floating-point types

# A simple float...
a = 123.456

# A float containing the integral value 2
b = 2.

# Leading zeros can be left off
c = .3 # same as 0.3

# Exponential / scientific representation
d = -123e-5

Two special cases are True and False, two constants that define the Boolean truth values. They behave similar to the integer values 0 and 1, except when they are converted into strings and return their names.

Example: Booleans.py

# booleans behave like integers, except when converted to strings.
# The built-in function "type" can be used to query the type of a value.
print("True:  ", True, type(True))
print("False: ", False, type(False))
print("1:     ", 1, type(1))
print("False + 0: ", False + 0, type(False + 0))
print("True * 5: ", True * 5, type(True * 5))

Resulting output:

Strings

In IronPython, strings are always in Unicode and any length. It does not make any difference if they are enclosed in ' or ". Strings can also have triple quotation marks """ or ''', which allows for multiline string literals.

Similar to C, special characters can be excluded by means of backslashes (\ ): As a comparison, the dollar sign ($) is used in IEC for this purpose.

There are also raw strings that have other rules for the backslash. This is practical when the string should have literal backslashes. Example: Windows file paths or regular expressions.

Example: Strings.py

# encoding:utf-8
from __future__ import print_function

a = "a simple string"
b = 'another string'
c = "strings may contain 'quotes' of the other type."
d = "multiple string literals" ' are concatenated ' '''by the parser'''
e = "Escaping: quotes: \" \' backslash: \\ newline: \r\n ascii code: \x40"
f = """triple-quoted strings may contain newlines, "single"
'quotes' and '''multiquotes''' of the other type"""
g = "Üňíçǿđȩ is also possible: 北京, Москва, Αθήνα, القاهرة"
h = r"c:\raw\strings\retain\backslashes.txt"

# we iterate over a sequence of all the variables defined above:
for i in (a,b,c,d,e,f,g,h):
    print(i) # prints the contents of the variable

Resulting output:

Python does not have characters types. Characters are expressed by the use of strings with a length of 1. In this way, iteration via a string, or indexing in a string, returns a single-character string.

See also

Lists and tuples (data sets)

Lists and tuples basically correspond to arrays in C and IEC, but there are some noticeable differences:

  • Index access is always checked. Accessing a list or a tuple with an invalid index throws an exception.
  • Both lists and tuples can contain elements of different types (also other lists and tuples). In contrast in C and IEC, arrays can contain only elements of a single type.
  • Lists are dynamic, and elements can be added, removed, or replaced at any time.
  • Tuples are not changeable: Once a tuple is created, it cannot be modified anymore.

Lists are created with the list() constructor. As an alternative, you can use brackets []. Tuples are created with the tuple() constructor or parentheses ().

Example: list_tuples.py

from __future__ import print_function
print("Testing tuples and lists")

# We define a tuple with the numbers from 1 to 10:
t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print("Tuple:", t)

# We can access the 6th element of the tuple.
# As in C, index counting starts with 0.
print("Element 5:", t[5])

# Subscription is more powerful using the range syntax:
print("Range[2:5]:", t[2:5]) # lower bound is inclusive, upper bound is exclusive.
print("Range[2\:\:2]:", t[2\:\:2]) # start with 3rd element, and print every 2nd element.
print("Range[-3:-1]:", t[-3:-1]) # Start with the 3rd last element, end just before the last element (upper bound is exclusive)
print("Range[\:\:-1]:", t[\:\:-1]) # negative step with - print backwards

# lists are similar to tuples...
l = [11, 12, 13, "8", t] # contains mixed types: 3 integers, a string, and the tuple defined above.
print("List:", l)

# ... but elements can be added or removed dynamically.
l.append(9) # Add a 9 to the list.
print("List with 9:", l)
print("List Range[3:6:2]:", l[3:6:2]) # print the 4th and 6th element.

del l[1] # remove the element at index 1, the 12.
print("Removed[1]:", l)
del l[1:3] # Remove the elements at index 1 and 2, the 13 and the '8'.
print("Removed[1:3]:", l)

Resulting output:

Dictionary

Python also has a hash table type ( also “hashmap”). In contrast to the list, it can be indexed with any elements, for example strings. Its constructor is dict() and its literals are declared with braces {}.

The sample script dictionaries.py creates the output displayed below. In the last line, the script is terminated with a “KeyError” exception:

Example: dictionaries.py

from __future__ import print_function
print("Testing dictionaries")

# Declare a dictionary with three entries, the third being a list
d = {1: "a", 2: "b", "my list": [1, 2, 3]}
print(d)

# print the value of the key 1
print(d[1])

# remove the value with the key "my list"
del d["my list"]

# Add a value 4 with the key 3
d[3] = 4
print(d)

# The "get" method returns the second argument if the key cannot be found.
print(d.get(1, 42))
print(d.get(23, 42))

# print all keys in the dictionary
for key in d:
    print(key)

# index access for unknown keys will throw a "KeyError" exception!
print(d[23])

Resulting output:

And then in the last line, the script terminates:

You can view the stack trace by clicking the Details button. Here you find out about line number 27 and the unknown key 23.