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
|
|
|
string = 'Beginning of string' string += ' and end of string' for word in string.split(): print(word) '+'.join(string.split(' ')) |
Beginning
|
|
|
def double(input): return 2 * input print(double(3)) |
6 |
|
|
x = 7 if x % 2 == 0: print('even number') else: print('odd number') |
odd number |
|
|
x = 7 try: print(x / 0) except Exception as e: print(str(e)) raise e finally: print('bye!') |
division by zero
Traceback (most recent call last):
|
|
|
myDict = {'one':1} print(myDict['one']) myDict['two'] = 'deux' print(myDict) |
1
|
|
|
myList = [1, 'string', {'one':1, 'two':2}] myList.append('one more') print(myList) |
[1, 'string', {'two': 2, 'one': 1}, 'one more'] |
|
|
list = [1, 2, 3, 4, 5] print([2*x fox x in list if x % 2 == 0]) |
[4, 8] |
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))