We’ve migrated our documentation to a new site, which means some URLs have changed.
Audience

Python Mini-Tutorial

 English  | 日本語

 

This schematic introduction to Python is only to cover the bare minimum required for being able to copy and paste Python code examples from the Cxense documentation and modifying them according to ones needs. For a more complete and in-depth introduction we recommend this tutorial found at the official Python site.

All example code is Python 3.x and that is what is used in the table below with the exception of the print functionality which is described both for 2.x and 3.x.

Python Script

Script Output

Learning Points

Python 3.x:

print("This is a string") print(6)

Python 2.x:

print "This is a string" print 6

This is a string
6

  • Python 2.x has a print statement and Python 3.x has a print() function

  • print() writes a line to standard output (that is, it adds a line feed to the input and dump it all to the terminal window)

  • Python does not use any end of command character such as for instance semi‐colon (';')

  • In Python a string starts and stops with a single (') or a double (") quote character.

  • The print function can print any variable type thrown at it

string = 'Beginning of string' string += ' and end of string' for word in string.split(): print(word) '+'.join(string.split(' '))

Beginning
of
string
and
end
of
string
Beginning+of+string+and+end+of+string

 

 

  • Strings can be concatenated using the '+' operator

  • The function string.split(delimiter) will convert a string into an array (called a list in Python) of strings. The default delimiter is space. Hence, string.split() is equivalent to string.split(' ')

  • There is no variable declaration in Python and the variable will take the type of the data (that can change over time)

  • The most commonly used for loop in Python is for (item in list): someActionWith(item)

  • Any class declaration, function declaration, loop or condition ends with a semi colon and what follows has to be indented (Python does not uses any kind of block begin/end marker such as for instance curly brackets)

  • delimiter.join(listOfStrings) does the exact opposite of string.split(delimiter). The latter split a string into a list of strings relative to some delimiter, the former put a list of strings together with a given delimiter as the 'glue'.

def double(input): return 2 * input print(double(3))

6

  • A python function declaration has this syntax def functionName(parameters):

  • The function stops where the indent level is back at the level of the function declaration

  • Return values are returned with the return statement

x = 7 if x % 2 == 0: print('even number') else: print('odd number')

odd number

  • A conditional statement does not need to be encapsulated in parentheses

  • Both if and else statements terminates with a colon and what follows has to be indented

  • Test for equality is done using double equal ('==')

x = 7 try: print(x / 0) except Exception as e: print(str(e)) raise e finally: print('bye!')

division by zero
bye!

Traceback (most recent call last):
...File "test.py", line 6, in <module>
......raise e
...File "test.py", line 3, in <module>
......print(x / 0)
ZeroDivisionError: division by zero

  • Try/catch/finally is try/except/finally in Python, throw is raise

  • Exception is the mother class of all types of exceptions

  • str() gives the string representation of any object

myDict = {'one':1} print(myDict['one']) myDict['two'] = 'deux' print(myDict)

1
{'one': 1, 'two': 'deux'}

  • A dictionary can hold any type of value, but the key must be hashable (normally a string or a number)

  • New key-value pairs are added with the syntax dict[newKey] = newValue

myList = [1, 'string', {'one':1, 'two':2}] myList.append('one more') print(myList)

[1, 'string', {'two': 2, 'one': 1}, 'one more']

  • A list (array) can hold any type of item (element)

  • One add a item to the list using the append() function

list = [1, 2, 3, 4, 5] print([2*x fox x in list if x % 2 == 0])

[4, 8]

  • List comprehension is a syntax that allows for less code to express more. The code to the left and below do the exact same thing.

list = [1, 2, 3, 4, 5] newList = [] for x in list: if x % 2 == 0: newList.append(2*x)  print(newList)

 

And here we have summed up most of it in one little script. What will the output be?

numbers = {'one':'1', 'two': 2, 'three':"3" } def replaceNumbers(inputStr): try: outputStr = '' for word in inputStr.split(): outputStr += ' ' if word in numbers: outputStr += str(numbers[word]) else: outputStr += word except Exception as e: print('Something went wrong: ' + str(e)) outputStr = 'Sorry, better luck another time!' finally: return outputStr string = "if two wrongs don't make one right, try three" print(replaceNumbers(string))

Click "Expand source" to see outputExpand source

if 2 wrongs don't make 1 right, try 3

 

The script below do the very same as the script above, just that this version uses list comprehension which leaves a smaller code footprint:

numbers = {'one':'1', 'two': 2, 'three':"3" } def replaceNumbers(inputStr): try: outPutstr = ' '.join([str(numbers[word]) if word in numbers else word for word in inputStr.split()]) except Exception as e: print('Something went wrong: ' + str(e)) outputStr = 'Sorry, better luck another time!' finally: return outPutstr string = "if two wrongs don't make one right, try three" print(replaceNumbers(string))

 

 

Last updated: