Python Basics

This section provides some basic knowledge about Python in general and can be skipped if Python is already known.

On the Internet there are a lot of good and detailed tutorials for Python. Since this chapter can only touch on many topics, it is recommended to use such a tutorial especially for beginners.

Python Scripts

A Python script is a sequence of text based instructions similar to a ToDo-list or a cooking recipe. It describes what the computer should do when and how, regarding to given conditions.

Python Modules and Packages

Python Module

A Python module is a text file with the file extension “.py” containing Python script code.

Python Package

A Python package is a folder that contains one ore more Python script files.
Additionally, the folder must contain an empty text file with the name __init__.py

Module and Package Names

For the naming of modules and packages, special rules (naming conventions) must be observed.
  • Modules should have short, all-lowercase names.

  • Underscores can be used in the module name if it improves readability.

  • Packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Statements

Instructions that a Python interpreter can execute are called statements.

  • ‘a = 1’ is an assignment statement

  • an ‘if’ statement defines a condition

  • ‘for’ statements and ‘while’ statements let the computer repeat certain lines of code.

Comments

It is very helpful and a good programming practice to add comments to the code to be able to understand later what the program does in detail.

Single line comments start with a hashtag ‘#’ followed by a space.

1
# This is a comment

A comment placed directly after a statement is called ‘inline comment” and should be avoided if possible. Inline comments should be separated by at least two spaces from the statement and should start with a ‘#’ and a single space.

1
a = b + c  # Inline comment

A comment block consists of several lines and is enclosed by three quotes in the first and in the last line.

1
2
3
4
5
"""
Comment line 1
Comment line 2
Comment line n
"""

Variables

A variable is a placeholder for a value stored in the memory that can be specified and changed while running a script.

It can be defined by choosing a name and assigning a value to it.

Note

A variable name mustn’t start with a digit, should be lowercase and can be separated with underscores.

1
2
3
4
5
bool_var = True         # A boolean assignment
integer_var = 100       # An integer assignment
floating_var = 1000.0   # A floating point
string_var = "John"     # A string variable
list_var = [1, 2, 3, 4] # A list of integers

Example:

The example shows a simple counter

1
2
3
4
5
6
7
count = 1
print(count)
# -> 1

count += 1
print(count)
# -> 2

Operators

Arithmetic operator examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Addition
c = a + b

# Subtraction
c = b - a

# Multiplication
c = a * b

# Division
c = a / b

Comparison operator examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Equal
a == b

# Unequal
a != b
a <> b

# Greater-than
a > b

# Less-than
a < b

Logical operator examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = True
b = False

# And
(a and b)  # -> False

# Or
(a or b)  # -> True

# Not
(not b)   # -> True

String operator examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
a = ""
b = "tree"
c = "house"
d = 1

# Concatenation
a = b + " " + a
print(a)
# -> "tree house"

# Due to Python cannot concatenate a string and integer,
# you must convert the integer to a string for concatenation.
a = b + " " + c  + str(d)
print(a)
# -> "tree house1"

If you want to use quotation marks or backslashes in a string, it is recommended to precede them with a backslash. The backslash is an escape character that tells Python that the following character has a special meaning.

1
2
a = "This is very \"special\""
b = "C:\\user\\"

A line break (CRLF) can be inserted into a string as follows:

1
2
3
CRLF = "\r\n"
a = "First line" + CRLF + "second line"
b = "First line\r\nsecond line"

Indention - Grouping of Statements

A belonging group of statements is called a code block. Unlike other computer languages, Python uses indentation to define a code block. Therefore leading whitespace (spaces and tabs) at the beginning of a logical line are used.

Note

The Narda Script Launcher API uses four spaces per indentation. The type of indentation must not be changed within a script!

Maximum Line Lenght

All lines of code should be limited to a maximum of 79 characters.
Longer code lines can be wrapped with a backslash.
1
2
3
a = 5
b = "This is a very, very, very, very long text with number " + str(a) + \
   "in it"

The program flow can be controlled by conditions and loops.

if, then, else Conditions

A program sequence can be controlled with if, then, else conditions.
A condition can have several statements/operations separated by linebreaks.
All statements that belong to a specific condition are grouped into a so called code block that is defined by indention.

Note

Unlike C / C++ which utilizes braces for code blocks, Python code blocks are separated by indentations. The Narda Script Launcher API uses four spaces per indentation. The type of indentation must not be changed within a script!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 1
b = 2
c = 3

if a > b:
   print("a > b")
elif b > c:
   print("b > c")
else:
   print("a < b and b < c")

Loop Statements

You can repeat parts of your program by the help of loop statements.
All statements that belong to a specific loop are grouped into a so called code block that is defined by indention.

Note

Unlike C / C++ which utilizes braces for code blocks, Python code blocks are separated by indentations. The Narda Script Launcher API uses four spaces per indentation. The type of indentation must not be changed within a script!

while-Loop

1
2
3
4
5
# Repeats the indented code until i reaches 50
i = 0
while i <= 50:
   print(i)
   i += 1

for-Loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# You can also define a range to loop through
# This example repeats the indented code until i reaches 50 starting with i = 10
for i in range(10, 50):
   print(i)

# You can loop through lists
items = ["bike ", "car", "truck"]
for item in items:
   print(item)

# You can break a loop by condition
items = ["bike ", "car", "truck"]
for item in items:
   print(item)
   if item == "car":
      break

# You can continue a loop by condition
items = ["bike ", "car", "do not print me", "truck"]
for item in items:
if item == "do not print me":
   continue
print(item)

Functions

If certain code sequences occur repeatedly at different places in a script, they can be packed into so-called functions.
This makes the code easier to understand and maintain and you can reuse some sequences in your code.

A function definition starts with the keyword ‘def’ followed by a function name, optional parameters and ends with a colon.

A Python function can return none, one or several values

You can add a description to your function surrounding the comment text by three quotes. This is called a docstring.
Unlike C/C++, function comments are place below the function definition in Python.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def add(a, b)
   """Simple function that calculates 'a + b' and returns the result"""
   return a + b

def add(a=0, b=0)
   """Function with optional parameters that calculates 'a + b' and returns the result"""
   return a + b

def add(a: float, b: float)
   """Function with parameters of defined data types that calculates 'a + b' and returns the result"""
   return a + b

def add(a: float=0, b: float=0)
   """Function with optional parameters of defined data types that calculates 'a + b' and returns the result"""
   return a + b

def concat(arg1: int, arg2: str="Text"):
   """Brief function description.

   :param arg1: This argument must be of type integer
   :type arg1: int
   :param arg2: This argument must be of type string and has the default value "Text"
   :type arg2: str
   :return: Returns the concatenated result and both arguments as Python tuple
   :rtype: (str, int, str)
   """
   result = arg2 + str(arg1)
   return result, arg1, arg2

Classes

Note

The topic of object-oriented programming with classes and methods offers many possibilities and is very complex. For the creation of simple scripts this knowledge is not necessary!

The following text should only give a short introduction for a better overview.

A class definition starts with the keyword ‘class’ followed by a class name, optional base classes and ends with a colon.

1
2
3
4
5
class Person:
 """The base class for a person"""

class Employee(Person):
    """Class, that is derived from the base class Person."""

It encapsulates data and class methods (functions).

You can define attributes and do initialization stuff in the optional class method ‘def __init__(‘. It will be called while instantiation.

The keyword ‘self.’ represents the instance of the class. It allows to access the attributes and methods of the class in python.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Person:
 """The base class for a person"""

 def __init__(self, name):
     self.name = name

 def identify(self):
     """Prints the name of the person"""
     print("name: " + self.name)
     print("----------------------------------------------")

Instantiation is the process by which a class is created in memory, initialized and assigned to a variable. The class then becomes a concrete object in memory.

1
2
3
# The variable John is assigned a concrete object of type Person
# with the name "John".
john = Person("John")

You can reuse and extend attributes and functions of a ‘base class’ by creating a new class that derives from the base class.

For proper initialization you have to call the ‘__init__’ method of the base class in the ‘__init__’ method of the derived class. This can be done with the keyword ‘super().’

Class Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Person:
 """The base class for a person"""

 def __init__(self, name):
     self.name = name

 def identify(self):
     """Prints the name of the person"""
     print("name: " + self.name)
     print("----------------------------------------------")


class Employee(Person):
    """Class, that is derived from the base class Person."""

    def __init__(self, name, personnel_no):
        super().__init__(name)
        self.personnel_no = personnel_no

    def identify(self):
        """Prints the name and the personnel number of the employee"""
        print("name: " + self.name)
        print("personnel no: " + str(self.personnel_no))
        print("----------------------------------------------")


class Visitor(Person):
    """Additional class, that is derived from the base class Person."""

    def __init__(self, name, company):
        super().__init__(name)
        self.company = company

    def identify(self):
        """Prints the name and the company of the visitor"""
        print("name: " + self.name)
        print("company: " + self.company)
        print("----------------------------------------------")

    # Instantiate a list of different persons based on the class Person


persons = []
persons.append(Person("John"))
persons.append(Employee("Bill", 4711))
persons.append(Visitor("Kate", "Logistics Ltd."))

# Loop through the list and print the identification.
for person in persons:
    person.identify()

Class Methods

Class methods are functions that belong to a class. The first parameter of a method is always ‘self’ which is a reference to the instance of the class. This allows you to access class variables within the method (like the variable name in the sample code below).

1
2
3
4
def identify(self)
   """Prints the name of the person"""
   print("name: " + self.name)
   print("----------------------------------------------")