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
Updated: 19.08.2024 | Formatting of strings changed
Vertec Python Functions

Structure of Python Code

  • End of line is marked by line break
  • If you want a statement to span several rows (for example, because 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 indentation.

Auxiliary functions

Function description

type(x)

Displays the type of the x value

dir(x)

Displays possible functions of the x type

help(x)

Displays help for the x type. (Attention: case-sensitive)
Example:

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

Comparisons

<

less than

<=

less than or equal to

>

greater than

>=

greater than or equal to

==

Equal

!=

not equal

< >

not equal

inf

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 be any number of rows (e.g. form definitions or , while single and double strings can be 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:

”Hi, my name is {} and I’m {} years old.”.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

Function 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 uppercase

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:

receiverStr = '; '.join(receiver)

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:

  • {:} – symbols for formatting
  • 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,” “Empi,” “Jun,” ...)

Dictionary

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

State = {“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

Function 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 x-th element from the list and removes it immediately. 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(list)>0:
    print pop()

is equal to

for entry in list:
    print entry
    del entry

index(x)

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

'abc’.index('c')

Result: 2

count(x)

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

'Hi, my name is Hans and I’m learning 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 <query>:
    <do>
elif <query>:
    <do>
else:
    <do>
Example
numbers = [1,2,3]
if 1 in numbers:
    print '1 available.'
else:
    print 'not available.'

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
user = vtcapp.currentlogin()
projectList = editor.evalocl(“myProjects->orderby(code)”)
for project in projectList:
    print projekt.code  # Members are addressed with periods.
Example of numbers
for i in xrange(1,11):
    print str(i)  # numbers from 1-10

while loop

while <query>:
    <do>
Example
i = 1
while i <= 10:
    print 'The number is {}'.format(i)
    i += 1

Create Function

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

Functional examples

Function Code (disambiguation)
Product of two numbers
Def product(a, b):
    return a*b
Active projects from a list
def getActive(projectlist):
    resList = []
    for project in projectList:
        if project.active:
            resList.append(project)
    return resList
Create an activity on a specific
project
def firstelleActivitaet(project):
    newAkt = vtcapp.createobject(“Activity)
    newAkt.projekt = project
    newAkt.bearbeiter = project.projectleiter

    # Activities
    vtcapp.showdetailform(newfile)
Make a list of projects two
active and inactive lists
def activeSplit(projectlist):
    for project in projectList:
        if project.active:
            aktive.append(project)
        else:
            inactive.append(project)
    return (active, inactive) # Tuple of Lists

The call would then look like this:

active, inactive = activeSeparate(projectList)
Bitte wählen Sie Ihren Standort