SPSS TUTORIALS FULL COURSE BASICS ANOVA REGRESSION FACTOR

# Python Operators – Quick Overview & Examples

The table below presents a quick overview of all Python operators.

Some basic examples for some operators very specific to Python are found below this overview.

OPERATORLOOKS LIKEFUNCTIONEXAMPLES
Is=Assigns value to objectmyString = 'Ruben'
Equal to==Compares if values are equalif myString == 'Chrissy':
Not equal to!=Compares if values are not equalif myString != 'Ruben':
Less than<Compares if value is less thanif myAge < 30:
Less than or equal to<=Compares if value is less than or equal toif myAge <= 30:
Greater than>Compares if value is greater thanif myAge > 30:
Greater than or equal to>=Compares if value is greater than or equal toif myAge >= 30:
Identity equalisChecks if objects have equal IDsif myAge is None:
Identity not equalis notChecks if objects have different IDsif myAge is not None:
IninChecks if object contains other objectif 'a' in 'banana':
AndandChecks if 2 conditions are both Trueif 'a' in 'banana' and 'c' in 'cherry':
OrorChecks if at least 1 of multiple conditions is Trueif 'a' in 'banana' or 'b' in 'cherry':
NotnotChecks if condition is Falseif not 'c' in 'banana':
Backslash\Escape (special or normal) characterprint('new line starts\nhere')
Hash#Indicates that rest of line if comment#LOOP OVER VARIABLES STARTS HERE
Square brackets[]Extracts part of object such as substring
Indicates Python list object
myString = 'Ruben'[0]
Parentheses()Combines conditions
Indicates Python tuple
if ('a' in 'banana' or 'b' in 'banana') and 'd' in 'cherry':
Curly brackets{}Placeholder for Python text replacement
Indicates Python dict object
'Just say {}!'.format('hello')
Add element to object such as concatenation
fullName = 'Ruben' + ' van den Berg'
Minus-Subtraction for numbers10 - 9
Asterisk*Multiplication for numbers10 * 9
Slash/Division for numbers10 / 2
Double asterisk**Power for numbers2 ** 10
Double slash//Floor division for numbers3 // 2
Percent%Modulus for numbers
Text replacement in strings
3 % 2
Add element to object such as concatenation
cntr += 1

## Python “Less Than” Operator

A minor note regarding the Python <, <=, > and >= operators is that they also apply to strings. In this case, they roughly refer to the alphabetical order of those strings.

begin program python3.
print('a' < 'b') # True
print('a' > 'b') # False
end program.

More precisely, the aforementioned operators compare if Unicode code points underlying characters are smaller/larger. This is why capital letters are always smaller than their lower case counterparts.

begin program python3.
print('a' < 'A') ## False
print('a' > 'A') ## True
end program.

Most (but not all) special characters precede all numbers, which precede all letters.

begin program python3.
print('#' < '5') # True
print('5' < 'Z') # True
end program.

## Python “Is” Operator

In Python, “is” evaluates if 2 objects share the same ID. When comparing Python objects, we usually compare if their values are equal. A stricter comparison, however, is whether their IDs are equal too. The syntax below shows a quick example.

*COMPARE STRING OBJECT WITH SAME VALUES, DIFFERENT IDS.

begin program python3.
myName = 'Ruben'
yourName = 'Rube'
yourName += 'n'
print(myName,yourName) # Ruben Ruben
print(myName == yourName) # True
print(id(myName),id(yourName)) # 51019032 51016008
print(myName is yourName) # False
end program.

If 2 objects have the same ID, then they are basically just different names for the same object. In this case, a change to one of them applies to the other as well.

*CREATE 2 LIST OBJECTS WITH SIMILAR IDS.

begin program python3.
myList = [1,3,5]
yourList = myList
print(myList is yourList) # True
myList.append(7) # Applies to 'both' lists
print(myList,yourList) # [1, 3, 5, 7] [1, 3, 5, 7]
end program.

*CREATE 2 LIST OBJECTS WITH DIFFERENT IDS.

begin program python3.
myList = [1,3,5]
yourList = myList[:]
print(myList is yourList) # False
myList.append(7) # Applies only to myList
print(myList,yourList) # [1, 3, 5, 7] [1, 3, 5]
end program.

## Python “In” Operator

The Python “in” operator evaluates if some object contains another object. Basic examples are

• does some Python string contain some substring?
• does some Python list contain some string?
• does some Python tuple contain some integer?
*CHECK IF STRING CONTAINS SUBTRING.

begin program python3.
myFruit = 'banana'
print('an' in myFruit) # True
end program.

*CHECK IF LIST CONTAINS SUBTRING.

begin program python3.
myFruit = ['apple','banana','cherry']
print('apple' in myFruit) # True
end program.

Note that the “in” operator is a bit tricky for Python dict objects: it only inspects if some object is among the dict keys, not its values.

*"IN" ONLY INSPECTS DICT KEYS, NOT VALUES.

begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print('a' in myFruit) # True
print('apple' in myFruit) # False
end program.

*USE "VALUES" METHOD FOR SEARCHING DICT VALUES.

begin program python3.
print('apple' in myFruit.values()) # True
end program.

## Backslashes in Python

In Python, a backslash indicates an escape sequence: a combination of 2 characters where the first modifies the meaning of the second. This works in 2 directions:

• a backslash gives a special meaning to “normal” characters and
• a backslash abolishes the special meaning of special characters.

A common example of the first type is \n, in which the backslash changes the meaning of the n from simply “n” to a line break.

begin program python3.
print('New line starts\nhere')
end program.

An example of the second type is \', in which the backslash changes the special meaning of ' (start of a string) to simply “'”.

begin program python3.
print('I don\'t know!') # I don't know!
end program.

For specifying paths in Python (especially when using the os module), we often need to escape the backslash itself. We do so by either using 2 backslashes or by specifying a path as a raw string by preceding it with “r”.

*ESCAPE BACKSLASHES WITH BACKSLASHES.

begin program python3.
myPath = 'D:\\SCRIPTS\\NEW FOLDER'
print(myPath) # D:\SCRIPTS\NEW FOLDER
end program.

*ESCAPE BACKSLASHES BY RAW STRING.

begin program python3.
yourPath = r'D:\SCRIPTS\NEW FOLDER'
print(yourPath) # D:\SCRIPTS\NEW FOLDER
end program.

## Square Brackets in Python

In Python, square brackets either

• extract a part from some object such as a substring or
• indicate a Python list object.

The syntax below gives a handful of examples for extracting elements from objects, a procedure known as “slicing” in Python.

*EXTRACT FIRST 5 CHARACTERS (=SUBSTRING) FROM STRING OBJECT.

begin program python3.
myName = 'Ruben Geert van den Berg'
print(myName[:5]) # Ruben
end program.

*EXTRACT LAST ELEMENT FROM TUPLE.

begin program python3.
myTuple = (1,3,5,7,9)
print(myTuple[-1]) # 9
end program.

*EXTRACT DICT VALUE FOR KEY = 'a'.

begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print(myFruit['a']) # apple
end program.

Square brackets around zero or more objects tell you that these make up a Python list object.

*CREATE EMPTY LIST OBJECT WITH SQUARE BRACKETS.

begin program python3.
animals = []
print(type(animals)) # <class 'list'>
end program.

begin program python3.
print(animals) # [] tells you that animals is a list object
end program.

## Parentheses in Python

In Python, parentheses either

As the examples below suggest, it may be a good idea to always use parentheses for combining 3 or more conditions using “and” and “or” operators.

*LAST CONDITION MUST BE TRUE.

begin program python3.
if ('a' in 'banana' or 'b' in 'banana') and 'd' in 'cherry':
print('Yes!')
else:
print('No!')
end program.

*FIRST CONDITION MUST BE TRUE.

begin program python3.
if 'a' in 'banana' or ('b' in 'banana' and 'd' in 'cherry'):
print('Yes!')
else:
print('No!')
end program.

*UNCLEAR HOW CONDITIONS COMBINE...

begin program python3.
if 'a' in 'banana' or 'b' in 'banana' and 'd' in 'cherry':
print('Yes!')
else:
print('No!')
end program.

## Curly Brackets in Python

In Python, curly brackets either

We'll cover different options for text replacements in SPSS Python Text Replacement Tutorial but we'll also add a minimal example below.

*USE {} AS PLACEHOLDER FOR TEXT REPLACEMENT.

begin program python3.
myGreeting = 'hello'
print('Just say {}!'.format(myGreeting))
end program.

The examples below demonstrate that curly brackets also indicate a Python dict object.

*USE {} TO INDICATE DICT OBJECT.

begin program python3.
myFruit = {'a':'apple','b':'banana','c':'cherry'}
print(myFruit) # {'c': 'cherry', 'b': 'banana', 'a': 'apple'}
print(type(myFruit)) # <class 'dict'>
end program.

## Python Plus Operator

In Python, the plus operator either

• adds 2 or more numbers (such as int or float objects) or
• adds 1 or more elements to an object.

The example below demonstrates numeric addition.

*NUMERIC ADDITION FOR FLOAT AND INT OBJECTS.

begin program python3.
myInt = 5
myFloat = 1.23
print(myInt + myFloat) # 6.23
end program.

For objects other than numbers -such as strings or lists- the plus operator adds elements to them. Like so, the examples below demonstrate a concatenation for a string object and adding a list to another list.

*PYTHON CONCATENATION WITH + OPERATOR.
begin program python3.
myDay = '23'
myMonth = 'February'
myYear = '2022'
myDate = myDay + ' ' + myMonth + ' ' + myYear
print(myDate) # 23 February 2022
end program.

*ADD LIST TO LIST WITH +. NOTE: USE += FOR CHANGING MYLIST.

begin program python3.
myList = [1,3,5]
print(myList + [7,9,11])
end program.

*ADD LIST TO LIST WITH EXTEND.

begin program python3.
myList = [1,3,5]
myList.extend([7,9,11])
print(myList)
end program.

## Double Asterisk in Python

A double asterisk in Python raises some number to some power.

*PRINT 2 RAISED TO THE ZEROETH THROUGH 9TH POWER.

begin program python3.
for pow in range(10):
print(2 ** pow)
end program.

Quick note: you can use something like myNumber**(1 / k) for finding the k-th root for some number, including the square root. In contrast to Excel, Googlesheet and SPSS, sqrt() is not available in Python unless you import the math module and use math.sqrt().

## Double Slash in Python

A double slash in Python is used for floor division: it divides x by y and truncates the result.

*FLOOR DIVISION OF 10 BY 3.

begin program python3.
print(10 // 3) # 3
end program.

## Percent Signs in Python

In Python, a percent sign is either used

• for the modulo function for numbers or
• as a placeholder for a text replacement in string objects.

First off, the modulo (not to be confused with modulus) returns the remainder after subtracting x from y as many times as possible. Like so, it can be used to check if numbers are odd or even.

*CHECK IF INTEGERS 0 THROUGH 9 ARE EVEN OR ODD NUMBERS.

begin program python3.
for myInt in range(10):
if (myInt % 2): # SHORTHAND FOR MODULO NOT ZERO
print('%s is an odd number.'%myInt)
else:
print('%s is an even number.'%myInt)
end program.

Second, percent signs are used as placeholders for text replacements in Python. Precisely,

• %s can be replaced by a string value,
• %d can be replaced by an integer number and
• %f can be replaced by a floating point number.

Note that these placeholders are somewhat deprecated over curly brackets with .format(). The syntax below shows minimal examples for both methods.

*TEXT REPLACEMENTS WITH % PLACEHOLDERS.

begin program python3.
name = 'Alexander'
age = 43
print('%s is %d years old.'%(name,age)) # Alexander is 43 years old.
end program.

*TEXT REPLACEMENTS WITH {} PLACEHOLDERS.

begin program python3.
name = 'Alexander'
age = 43
print('{} is {} years old.'.format(name,age)) # Alexander is 43 years old.
end program.

## Python Plus-Is Operator

In Python, the plus-is operator is used for

• adding a number to another number or
• adding an element to some other object.

In either case, a += b is nothing more than a shorthand for a = a + b. The syntax below gives a quick example for numeric objects.

*ADD 3 TO MYINTO VIA PLUS OPERATOR.

begin program python3.
myInt = 5
myInt = myInt + 3
print(myInt) # 8
end program.

*ADD 3 TO MYINTO VIA PLUS-IS OPERATOR.

begin program python3.
myInt = 5
myInt += 3
print(myInt) # 8
end program.

Apart from numeric addition, the += operator can also be used for concatenating strings or adding elements to Python list objects. In the latter case, it acts as .extend rather than .append as shown below.

*CONCATENATE TO STRING WITH += OPERATOR.

begin program python3.
myVars = ''
for ind in range(10):
myVars += 'v%s '%ind
print(myVars) # ['v0', 'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9']
end program.

*FOR LIST, += OPERATOR IS SIMILAR TO EXTEND (NOT APPEND).

begin program python3.
myVars = []
for ind in range(10):
myVars += ['v' + str(ind)]
print(myVars) # v0 v1 v2 v3 v4 v5 v6 v7 v8 v9
end program.

Right, so I guess that should do regarding Python operators. If you've any questions or remarks, please let us know.