Python Operators

This is part of my Python & Django Series which can be found here including information on how to download all the source code.

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Membership Operators
  6. Identity Operators
  7. Bitwise Operators
  8. Operator Precedence

Arithmetic Operators

Arithmetic operators allow simple mathematical calculations between two operators.

Where 1 + 2 = 3. The operator is +, the LHS operator is 1, the RHS operator is 2 and the result is 3.

Operator Operator Name Description Example Output
+ Addition Adds the LHS to the RHS 1 + 1 2
Subtraction Subtracts the RHS from the LHS 2 – 1 1
* Multiplication Multiples the LHS with the RHS 2 * 3 6
** Power Of LHS to the Power of the RHS 2 ** 3 8 ( 2 * 2 * 2 )
/ Division LHS Divided by RHS 10 / 3 3.3333333333333335
// Floor Division LHS Divided by RHS. The result is rounded down to the nearest integer 10 // 3 3
% Modulus The remainder if whole division is made 10 % 3 1 (9 + 1 )

Assignment Operators

Assignment operators permit assigning the result of an operation onto a variable.

All of the following assume that output is assigned a value of 10.

Operator Operator Name Description Example Output
= Assignment Assigns the value output = 1 1
+= Addition & assignment Assigns the addition of the two values output += 2 12
-= Subtraction & assignment Assigns the subtraction of the RHS from the LHS output -= 1 9
*= Multiplication & assignment Assigns the multiplication of the two values output *= 3 30
/= Division & assignment Assigns the LHS divided by the RHS output /= 3 3.3..
%= Modulus & assignment Assigns remainder of the LHS divided by the RHS output %= 3 1
**= PowerOf & assignment Assigns LHS to the power of the RHS output **= 3 1000
//= Floor/Int Division & assignment Assigns LHS divided by the RHS and rounded down to the nearest integer output //= 3 3

Comparison Operators

Comparison operators allow comparing one variable to another to determine the relationship between each others value.

Operator Operator Name Description Example Output
== Equality True if the LHS is equal to the RHS 1 == 1 True
!= Inequality True if the LHS is not equal to the RHS 1 != 2 True
> Greater than True if LHS is greater than to RHS 2 > 1 True
< Less than True if LHS is less than to RHS 1 =** Greater than or equal to | True if LHS is greater than or equal to RHS | 1 >= 1 | True
<= Less than or equal to True if LHS is less than or equal to RHS 1 True

Where two or more variables point to a primitive type or string, identity will resolve to true if the items are equal. This is because Python, for performance reasons, will only actually create one physical data entry in memory, with all variables pointing to the same data.

In fact in Python there is no concept of primitive types, everything is actually represented as a class.

Code:

1 is 1

Output:

True

Interestingly two empty tuples are considered identical but dictionaries and lists are not.

Code:

<br />print("Tuples: ", () is ())

print("Dictionaries: ", [] is [])

print("Lists: ", {} is {})

Output:

Tuples: True Dictionaries: False Lists: False

This is because tuples along with strings, int, float and booleans are immutable, their data can never change after being created. Python will only ever create one version of each entity considered equal. Creating multiple empty tuples or multiple integers of value one will always point to the same first created instance of that value.

Dictionaries and lists are mutable, their data can be changed. Python will therefore always create a new instance of Dictionary or List in preparation for when the data changes.

Bitwise Operators

Bitwise operators allow interrogation and manipulation of variables data at the bit level.

First lets take two variables and format them to the terminal. The ‘b’ string format command allows representing a variable as its raw binary data formatted as a string, allowing us to see the 0/1 of each bit in their ordinal position.

Code:

one = 111
two = 222

print('one: {0:b}'.format(one))
print('two: {0:b}'.format(two))

Output:

one: 001101111 two: 101001101

Please note above the preceding 00 have been added in for clarity.

Operator Description Example Output
& Each bit at the same ordinal position are performed AND operator one & two 1001101
| Each bit at the same ordinal position are performed OR operator one | two 101101111
^ Each bit at the same ordinal position are performed XOR operator, true if either is true but not both one ^ two 100100010
~ Bitwise inversion. Each bit is flipped. 0 -> 1 and 1 -> 0 ~one -1110000
>> Bitwise shift right. Bits all move to the right x places. First x bits are truncated one >> 2) 11011
<< Bitwise shift left. Bits all move to the left x place. First x bits become 0's one <> <<** Bitwise shift right and left
& Bitwise and
^ | Bitwise xor and or
<= >= Comparison operators
** == !=** Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

It is bad practice to rely on operator precedence. Use brackets to increase code reliability.

Code:

print( 1 + (2 * 3)  = 1 + 2 * 3)

Output:

True

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s