User Tools

Site Tools


script:walkthrough:operator_expressions

Operator expressions

Addition

$ print 'Numbers:', 1 + 1, -.5 + .5
Numbers: 2 0

$ print 'Larger than 32-bit:', \
  0xffffffffff + 0xffffffffff
Larger than 32-bit: 2.19902e+12

$ print 'Text:', 'Hello' + 'World'
Text: HelloWorld

$ print 'Array:', [1, 2, 3] + ['a', 'b', 'c']
Array: [ 1, 2, 3, a, b, c ]

$ print 'Dictionary:', \
  {1:2, 3:4} + {'a':'b', 'c':'d'}
Dictionary: { 1: 2, 3: 4, a: b, c: d }

$ print 'Time:', Time() + 3600
Time: 2019-11-19 22:56:53.514

Subtraction

$ print 'Numbers:', 1 - 1, -.5 - .5
Numbers: 0 -1

$ print 'Larger than 32-bit:', 0xffffffffff - 0xffffffffff
Larger than 32-bit: 0

$ print 'Dictionary:', {'a':'A', 'b':'B'} - 'a'
Dictionary: { b: B }

$ print 'Time:', Time() - 3600, timedelta(Time(), Time() - 3600)
Time: 2019-11-19 20:56:53.514 -3600

Multiplication

$ print 'Numbers:', 1 * 2, 2.5 * 4, (2 + 6) * 45
Numbers: 2 10 360

$ print 'Text:', 'Word' * 3, 'Longword' * 3.5
Text: WordWordWord LongwordLongwordLongwordLong

Division/concatenation

All numbers are internally floating point, so the result of integer division is not forced to be an integer.

$ print 'Numbers:', 2 / 2, 10 / 4, 1 / 0
Numbers: 1 2.5 inf

The / operator is also used for concatenating file paths. It automatically removes duplicate slashes at the end of a segment.

$ print 'Path concatenation:', \
    'folder' / 'filename.ext', \
    'folder/' / 'filename.ext'
Path concatenation: folder/filename.ext folder/filename.ext

If the right-hand argument begins with a slash (absolute path), the left-hand argument is ignored as the absolute path overrides it.

$ print 'Absolute:', 'base/path' / '/root/location'
Absolute: /root/location

Modulo

Modulo converts number arguments to integers.

$ print 'Numbers:', 7 % 3
Numbers: 1

% is also used for C-like formatted string interpolation. The right-hand argument can be a single value or an array of values.

$ print '%s with "%3i" arguments. Hex %x, capital hex %X, float %f, precision %.10f.' % [
    'Formatted', 2, 240, 240, Pi, Pi]
Formatted with "  2" arguments. Hex 0xf0, capital hex 0xF0, float 3.142, precision 3.1415926536.

$ print 'Width and precision: "%10.5f"' % Pi
Width and precision: "   3.14159"

Combined assignment operators

Combined assignment operators work on existing variables only. They are considered expressions, which means they can appear in arguments like in the example below.

$ a = 1
  
$ print 'a =', a += 3
a = 4

$ print 'a =', a -= 3
a = 1

$ print 'a =', a *= 100
a = 100

$ print 'a =', a /= 10
a = 10

$ print 'a =', a %= 3
a = 1

$ path = '/some/path/'

$ print 'path =', path
path = /some/path/

$ print 'path =', path /= 'filename.ext'
path = /some/path/filename.ext

Subscript

The subscript operator [] works on arrays and strings to extract elements/characters.

$ transports = ['planes', 'trains', 'automobiles', 'bicycles']

$ print transports[2]
automobiles

Negative indices are counted from the end of the array.

$ print transports[-1]
bicycles

The subscript operator is also used to access dictionaries by key.

$ xlat = {'hi': 'hello', 'globe': 'world'}

$ print xlat['hi'], xlat['globe']
hello world

Arrays can be nested.

$ matrix = [[1, 2], [3, 4]]

$ print 'Two-level indexing:', matrix[0][1], matrix[1][1]
Two-level indexing: 2 4

$ matrix2 = [matrix, matrix]

$ print matrix2[1][1][0], 'from', matrix2
3 from [ [ [ 1, 2 ], [ 3, 4 ] ], [ [ 1, 2 ], [ 3, 4 ] ] ]

Slice

The slice operator is versatile tool for extracting a subset from an array or a text string. It takes a range of indices as argument. If the start of the slice range is omitted, the slice begins from the start of the array. Omitting the end of the range works similarly.

$ fullArray = [1, 2, 3, 4, 5, 6, 7]
  
$ print 'Sliced:', fullArray[2:4], fullArray[3:], fullArray[:3]
Sliced: [ 3, 4 ] [ 4, 5, 6, 7 ] [ 1, 2, 3 ]

Slice arguments can be expressions.

$ print fullArray[0:len(fullArray)]
[ 1, 2, 3, 4, 5, 6, 7 ]

The slice range may use negative indices, too.

$ print 'Nega-sliced:', fullArray[-3:-1]
Nega-sliced: [ 5, 6 ]

An optional third parameter can be provided to specify the step size within the slice range.

$ print 'Stepping:', fullArray[::2], fullArray[1:6:2]
Stepping: [ 1, 3, 5, 7 ] [ 2, 4, 6 ]

The step value can be negative to reverse the resulting slice.

$ print 'Reverse slice:', fullArray[4:2:-1]
Reverse slice: [ 5, 4 ]

The slice operator can therefore be used to easily reverse an array.

$ print 'Reversing:', fullArray[::-1]
[ 7, 6, 5, 4, 3, 2, 1 ]

In addition to arrays, slices work on text strings as well.

$ fullString = "abcdefg"

$ print 'Sliced:', fullString[2:4], fullString[3:], fullString[:3]
Sliced: cd defg abc

$ print 'Nega-sliced:', fullString[-4:-2]
Nega-sliced: de

$ print 'Stepping:', fullString[::2], fullString[1:6:2]
Stepping: aceg bdf

$ print 'Reverse slice:', fullString[4:2:-1]
Reverse slice: ed

$ print 'Reversing:', fullString[::-1]
Reversing: gfedcba

Logical operators

The not operator negates its argument.

$ print not True
False

$ print not False
True

A non-empty text string is considered a boolean truth, so negation yields False.

$ print not 'Is this true?'
False

and and or perform the corresponding logical operations.

$ print True and False
False

$ print True or False
True

and has higher precedence than or.

$ print True or True and False
True

Early termination applies to both operators.

# Helper function to see what gets evaluated.
def showValue(a)
    print 'called with', a
    return a
end

$ showValue(True) and showValue(True)
called with True
called with True

$ showValue(False) and showValue(True)
called with False

$ showValue(False) or showValue(True)
called with False
called with True

$ showValue(True) or showValue(True)
called with True

Comparison

The usual set of comparison operators is available.

$ print 'Numbers:', 1 > 3, 1 < 3, 2 >= 2, 4 >= 2, \
        2 <= 2, 4 <= 2
Numbers: False True True True True False

Text string comparison is case sensitive.

$ print 'Text:', "hello" > "world", "hello" < "world", \
        'hello' == 'hello'
Text: False True True

$ print 'True/False:', True == True, True != False
True/False: True True

With arrays, the comparison is done for each element starting from the first one, until a difference is found.

$ print 'Arrays:', [1, 0] == [1, 0], [1, 0] < [1, 1], [1, 0] > [1, 1], [2, 0] > [1, 0], [2, 0] < [1, 0]
Arrays: True True False True False

Arrays of different lengths are compared solely based on the lengths.

$ print [100] < [1, 2]
True

Membership

The in operator checks whether the left-hand operand can be found within the right-hand operand.

$ transports = ['planes', 'trains', 'automobiles', 'bicycles']

$ print 'bicycles' in transports
True

$ print 'jet' in transports
False

in also works for text strings and dictionary keys.

$ print 'x' in 'abc'
False

$ print 'b' in {'a': 1, 'b': 2}
True
script/walkthrough/operator_expressions.txt · Last modified: 2019-11-20 10:24 by skyjake