Python programming

Introduction to Python Programming

Product line

Standard

|

Expert

Operating mode

CLOUD ABO

|

ON-PREMISES

Modules

Services & CRM

Budget & Phases

Purchases

Resource Planning

Business Intelligence

Created: 22.02.2010
Machine translated
Updated: 19.08.2024 | Added link to Python Standard Library

Vertec Python Features

Python Standard Library

Structure of python code

  • The end of a row is marked by a line break. If you want a statement to span several rows (for example, because otherwise the code will be very long and unreadable), you can insert a backslash \ at the end of the row. The line break will not be interpreted as such.
  • A block is formed by indenting. All equally indented rows belong to the same block.
  • Python is case-sensitive, which means that case-sensitive.

Auxiliary Functions

feature description

type(x)

Displays the type of the x value

dir(x)

Displays possible features of the x type

help(x)

Displays help for the x type. (Caution: case-sensitive)
Examples:

help(vtcapp)

help(vtcapp.getwithsql)

print 'text’

Prints the text in the debug window.

int(x) Conversion to Integer
float(x) Conversion to Float
str(x) Conversion to String

Blocks

In Python, blocks are formed by indentation. This means that all rows belonging to the same level must be indented equally (watch for tabs):

if x ==1:
    y = 2

If a block does not (yet) contain a code, a “pass” must be set as a wildcard.

if x == 1:
    pass

Variables

Variables can be assigned easily. The data type is automatically recognized by the assignment. Here, too, it is important to pay attention to the case.

bearb = vtcapp.currentlogin()

Difference between local and global variables:

  • Local variables can only be used within the feature and must be passed as parameters for each use in a different feature.
  • Global variables are initialized once and are available in the same script in each feature.

Global variables are declared outside of features. To use a global variable within a feature, it must be loaded with global:

leistung = argobject # globale Variable deklarieren

def WertExtAendern(betrag): 
    global leistung # globale Variable verwenden 
    leistung.xWertExt = betrag 

def BearbeiterSetzen(bearbeiter): 
    global leistung 
    leistung.bearbeiter = bearbeiter

Comparisons

<

less than

<=

less than or equal to

>

greater than

>=

greater than or equal to

==

Equal

!=

not equal

< >

not equal

INFs

Identical

INFs not

not identical

x in s

x present in list s

x not in s

x not present in list s

More Information

https://docs.python.org/library/stdtypes.html#comparisons

Strings

Defining strings

There are three ways to define strings in Python:

  • 'String’
  • ”String”
  • ”"”String”"”

The string must be closed with the same symbol with which it is opened. Triple strings (“"”) can span any number of rows (e.g. form definitions or , while single and double strings can span one row each:

Single-line

'string1' or “string1”

Multi-line

”"”line1

row2

line3”"”

Formatting strings

In the string, the placeholders are defined with curly brackets and with the method .format() passed in a tuple:

"Hallo, mein Name ist {} und ich bin {} Jahre alt.".format("Tobias", 18)

This variant in Python is very neat, since all variables are specified at the end. The string is displayed in its entirety and is not separated by special characters like [+, &].

If you want to output multiple lines of text, for example an address, you can insert a line break with \n.

Substrings

A string is treated like a list in Python. The individual symbols can be iterated.

a[0:]

Substring of a: from 1st symbol... all symbols

a[0:2]

Substring of a: from 1st symbol... 2 symbols

a[3:len(a)-1]

Substring of a: from 4th symbol... to penultimate symbol

a[:5]

Substring of a: the first 5 symbols

a[-1]

Last entry in the list

a + “test”

Attach String

Important String Functions

feature description

len(a)

The length of a string.

a.strip()

Removes all spaces to the left and right of the string.

a.lower()

Convert symbols to lowercase

a.upper()

Convert symbols to capital letters

a.isdigit()

Checks if the string is a number. If True, then conversion is possible.

a.replace('1', '2')

Find, Replace. Return value is the changed string.

a.split(',')

Separates the string with the specified separator and returns a list.

a.find('hurry’)

Finds the substring in the string. Returns the index if found. Otherwise -1

a.index('hurry’)

Finds the substring in the string. Returns the index if found. Otherwise ValueError. Useful in a Try...except.

str.join(list)

The join method returns a string containing all the elements of the passed list, separated by str. Example:

empfaengerStr = '; '.join(empfaenger)

You can get all the available string functions with the command:

help(str)

Paths in python strings

If you want to pass a path in Python, you have to be careful because backslashes in Python are used to encode control characters in strings. For example, the path C:\Documentation\temporary documents\.. becomes C:\Documentation emporary documents\.. and is invalid because \t is interpreted as a tab character. There are two ways to solve this problem:

  • Either double all backslashes, i.e. 'C:\\Documentation\\temporary documents\\...'. Of course, this can only be done by typing the path “by hand”.
  • “raw string,” which does not interpret any control characters. To do this, simply put an r immediately before the path: path = r’C:\documentation\temporary documents\...'.

More Information

https://docs.python.org/library/stdtypes.html#string-methods

https://docs.python.org/library/stdtypes.html#string-formatting-operations

Numbers

Initialize numeric values

Depending on how a value is initialized, it receives a specific data type. For example, the initialization a = 5 is interpreted as an integer. If you want to initialize the number as a float, you must specify a = 5.0 instead.

InitializationValue data type

a = 5

Integer

a = 5.0

Float

a = 4.35

Float

For information about the different number formats, use the help function:

  • help(int)
  • help(float)

Operations with numbers

Operationdescription

a + 6

Addition

a – 2

Subtract

a * 10

Multiplication

a / 10

Division

10.0 // 10

Division -> integer

pow(a, 2)a ** 2

Potency

5 % 2

Modular

For an operation with integer values, the result is an integer value:

10 / 4 = 2 (integer value of 2.5)

The same operation with a float value gives the following result:

10.0 / 4 = 2.5

or

float(10) / 4 = 2.5

This means: If one of the values is a float, the result is always output as a float:

1.5 * 7 = 10.5

1.5 * 6 = 9.0 (float value of 9)

Format numbers

The number representation is formatted as follows:

  • {:} – Formatting symbol
  • 0 – Prefix is 0
  • 6 – Length of number
  • 2 – Quantity of decimal places
  • f – Float
Example
'{:06.2f}'.format(555.3)

Result: 555.30

More Information

https://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex

Collection types in python

There are 3 different collection types in Python.

List

The usual list. A collection of items of different types.

list = []

list = [1,2,3]

list = [“a,” 2, obj]

Tuple

A tuple is a variable of several values. The tuple is not changeable. It is a constant list, so to speak.

Tuples are used for coordinate numbers, for example, where a tuple corresponds to a data point.

Data point1 = (5.1)

Data points = [(1,1),(2,2),(3,3)] # List of Tuple’s

Months = (“Jan,” “Feb,” “Mar,” “Apr,” “May,” “Jun,” ...)

Dictionary

A dictionary is a collection of data that saves the value and a unique key.

Cantons = {“ZH”: “Zurich,” “ZG”: “Zug”}

Weekdays = {1: “Mon,” 2: “Tue,” 3: “Wed,” 4: “Thursday,” 5: “Fri”}

The first part is the key and must be clear.

Important List Functions

feature description

append(x)

Add element [x]

insert(idx, x)

Add element [x] at position [idx]

remove(x)

Remove item [x]

reverse()

Reverse the order of items in the list.

pop([x])

Returns the xth item from the list and immediately removes it. Can be used well together with a While loop to iterate in a list.

pop() with no parameters returns the last item in the list.

while Len(liste)>0:
    print pop()

is equal to

for eintrag in liste:
    print eintrag
    del eintrag

index(x)

Returns the index of element [x], if present. Otherwise, a ValueError is returned. This feature can also be used for strings.

'abc'.index('c')

Result: 2

count(x)

Specifies the quantity of times element [x] occurs in the list. This feature can also be used for strings.

'Hallo, mein Name ist Hans und ich lerne Python.'.count(' ')

Result: 8

str.join(list)

Returns the list as a string. Is a string function.

xrange

xrange returns a list of numbers used primarily in for loops.

xrange(from, to, [step])

Examples of number lists:

xrange(1,3)

  • Result: [1,2]

xrange(0,10,2)

  • Result: [0,2,4,6,8]

xrange(1,12,3)

  • Result: [1,4,7,10]

More Information

https://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange

Looping in python

In Python, there is the if query, the for loop, and the while loop.

if query

if <Abfrage>:
    <do>
elif <Abfrage>:
    <do>
else:
    <do>
Example
zahlen = [1,2,3]
if 1 in zahlen:
    print '1 vorhanden.'
else:
    print 'nicht vorhanden.'

for loop

for <variable> in <liste>:
    <do>

The For loop in Python knows the beginning and end by indentation and therefore does not need a Next.

Example
bearbeiter = vtcapp.currentlogin()
projektListe = bearbeiter.evalocl("eigProjekte->orderby(code)")
for projekt in projektListe:
    print projekt.code  # Members werden mit Punkt angesprochen.
Example Of Numbers
for i in xrange(1,11):
    print str(i)  # Zahlen von 1-10

while loop

while <Abfrage>:
    <do>
Example
i = 1
while i <= 10:
    print 'Die Zahl ist {}'.format(i)
    i += 1

Create features

In Python, features are started with the def keyword. The return value is returned with the return keyword. In Python, there is no distinction between feature and procedure. Both are called def. The feature returns something and the procedure does not.

def ChangeText(leist):
    leist.text = ...

After that, it can be accessed in the code:

ChangeText(argobject)

Functional Examples

feature Code (disambiguation)
Product of two numbers
def produkt(a, b):
    return a*b
Active projects from a list
def getAktive(projektListe):
    resList = []
    for projekt in projektListe:
        if projekt.aktiv:
            resList.append(projekt)
    return resList
Create an activity on a specific
project
def erstelleAktivitaet(projekt):
    newAkt = vtcapp.createobject("Aktivitaet")
    newAkt.projekt = projekt
    newAkt.bearbeiter = projekt.projektleiter

    # Aktivitaet anzeigen
    vtcapp.showdetailform(newAkt)
Make a list of projects two
active and inactive lists
def aktiveTrennen(projektListe):
    for projekt in projektListe:
        if projekt.aktiv:
            aktive.append(projekt)
        else:
            inaktive.append(projekt)
    return (aktive, inaktive) # Tuple of Lists

The call would then look like this:

aktive, inaktive = aktiveTrennen(projektListe)

Calling features without parameters

When calling a feature that does not expect any parameters, it is very important that the parentheses are not forgotten. Example:

vtcapp.currentlogin #Falsch, Funktion wird nicht aufgerufen, es wird eine Fehlermeldung ausgegeben
vtcapp.currentlogin() #Richtig