HomeArchitectureMoving up the stack - time to learn python - part 3

# Moving up the stack – time to learn python – part 3

-

In our last article on my journey into Python, we explained at a high level the differences between an object-orientated programming language and a procedural one. We discussed the various Python variables and types, finishing with a very brief introduction to methods.

To refresh your memory on the first two articles, you can read them at the links shown below:

Today we will continue looking at the building blocks of Python by looking at how Python handles basic operators.

## What are basic operators?

In programming, Basic operators are symbols or keywords that perform some operation on one or more values or variables. For example, the operator “+” can add two numbers or concatenate (join) two strings. These operators can be classified into different types based on the number of operands they take (An Operand is an object that is being operated on, for example, with the sum 2 + 3 the operands are 2 and 3), the data types they work with (for example, date, time), and the kind of operation they perform.

Python uses many operators also found in other programming languages. Python also has some unique operators, such as identity, membership, and exponentiation operators. Operators in Python have a defined order of precedence, which determines how expressions are evaluated when multiple operators are present.  Python divides operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

### Arithmetic Operators

The basic Arithmetic operators in Python are “+” addition, “-“ subtraction, “*” multiplication, “/” division, “**” exponentiation, “//” floor division and finally “%” modulus. The first four operators hopefully do not need any further explanation; the last three may need a bit of explanation unless you have a background in Mathematics or can remember your high-school maths. 😊

#### Exponentiation

In Maths, Exponentiation is an operation involving two numbers, the base and the exponent or power. It is written as “b^n”, where “b” is the base and “n” is the power; this is pronounced as “b raised to the power of n”.  In general, exponentiation can be thought of as repeated multiplication.  In Python, exponentiation is performed using the “**” operator; this operator is placed between the base and the power. For example, “2 ** 3” means “2 x 2 x 2”, which equals “8”. You can also exponentiate values with the built-in “pow()” function, which accepts two arguments: the base and the exponent. For example, ”pow(2, 3)” also returns 8.

#### Floor Division

Floor division is an operation in Python that divides two numbers and rounds the result down to the nearest integer. The floor division happens via the double-backslash “//” operator. For example, “7 // 2 returns 3”.  A critical thing to remember is that the number is always rounded down, even if the remaining floating number is above “0.5”.

#### Modulus

Modulus or modulo is an arithmetic operation that gives the remainder when one number is divided by another. In Python, the modulus operator is represented by the percentage symbol “%”. It can be used for both integers and floating-point numbers. The syntax is “a%b”, where “a” is the dividend and “b” is the divisor.

### Arithmetic Operators examples

Below we have a number of scripts that give examples of each of the Arithmetic operators

```a = 5
b = 3
print(a + b)```

```a = 5
b = 3
print(a - b)```

```a = 5
b = 3
print(a * b)```

```a = 5
b = 3
print(a / b)```

```a = 5
b = 3
print(a ** b)```

```a = 5
b = 3
print(a // b)```

#### # Modulus

```a = 5
b = 3
print(a % b)```

The following simple script shows the output of the above snippits:

```a = 5
b = 3
result1 = (a+b)
result2 = (a-b)
result3 = (a*b)
result4 = (a/b)
result5 = (a**b)
result6 = (a//b)
result7 = (a%b)
print("Example Subtraction = ", result2)
print("Example Multiplication =", result3)
print("Example Division =", result4)
print("Example Expoentiation = ", result5)
print("Example Floor Division = ", result6)
print("Example Modulus = ", result7)```

Running this script will result in the following response: One thing to note is that Python correctly follows the order PEMDAS of operators for Math Calculations.  For completeness it have included below:

Parentheses,

Exponents,

Multiplication,

Division,

Subtraction.

This means that if you ask Python to calculate the sum “2+3*4” it will carry out the multiplication 3*4 before it carries out the 2+3, and the result will be 14.

## Assignment operators

Next we will look at Assignment Operators, In Python assignment operators are used to assign values to variables. The most common assignment operator is the equals sign (=). Other assignment operators include “+=”, “-=”, “*=”, “/=”, “//=”, “%=”, and “**=”. These operators perform arithmetic operations on the variable and then assign the result back to the variable, the following table highlights each option and together with its usage.

 Operator Description Syntax = Assign value of right side of expression to left side operand x = y + z += Add and Assign: Add right side operand with left side operand and then assign to left operand a += b -= Subtract AND: Subtract the right operand from the left operand and then assign to the left operand: True if both operands are equal a -= b *= Multiply AND: Multiply the right operand with the left operand and then assign it to the left operand a *= b /= Divide AND: Divide left operand with right operand and then assign to left operand a /= b %= Modulus AND: Takes modulus using left and right operands and assigns the result to the left operand a %= b //= Divide(floor) AND: Divide the left operand with the right operand and then assign the value(floor) to the left operand a //= b **= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a **= b &= Performs Bitwise AND on operands and assigns value to left operand a &= b |= Performs Bitwise OR on operands and assigns value to left operand a |= b ^= Performs Bitwise xOR on operands and assigns value to left operand a ^= b >>= Performs Bitwise right shift on operands and assigns value to left operand a >>= b <<= Performs Bitwise left shift on operands and assigns value to left operand a <<= b

The most common assignment operator is the equals “=” operator, which acts as the equals sign.

```a = 3
b=5
c=a+b
output(c)```

Any numbers and arithmetic operators to the operator’s right give the result to the operator’s left. In our case, our output will be “7” The same output can be obtained by using the “+” operand with the “=” operand

```X = 4
X += 3
Print(x)```

As shown below. Other examples are shown below, together with an explanation of what the snippet is actually doing.  Our first snippet assigns the value “5” to the variable “x” and then prints the value of “x”, which is “5”.

```x = 5
print(x)```

The second snippet adds “3” to the value of “x” (which is currently “5”) and then prints the new value of “x”, which is “9”.

```x = 5
x += 4
print(x)```

The third snippet subtracts “4” from the value of “x” (which has been redefined to “5”) and then prints the new value of “x”, which is “1”.

```x = 5
x -= 4
print(x)```

The fourth snippet multiplies the value of “x” (which is “5”) by “4” and then prints the new value of “x”, which is “20”.

```x = 5
x *= 4
print(x)```

The fifth snippet divides the value of “x” (redefined to “5”) by “4” and then prints the new value of “x”, which is “1.25”.

```x = 5
x /= 4
print(x)```

The sixth snippet takes the remainder when dividing the value of “x” (again “5”) by “3” and then prints the new value of “x”, which is “1”.

```x = 5
x %= 4
print(x)```

our seventh snippet performs integer division on the value of “x” (again “5”) by “4” and then prints the new value of “x”, which is “1”.

```x = 5
x //= 4
print(x)```

our final snippet raises the value of “x” (currently “5”) to the power of “4” and then prints the new value of “x”, which results in “625”.

```x = 5
x **= 4
print(x)```

Our script is below:

```x = 5
x += 4
print("the same output is obtained using += characters = ",x)
x = 5
x -= 4
print("Subtraction can be obtained using -= characters = ",x)
x = 5
x *= 4
print("Multiplication can be obtained using *= characters = ",x)
x = 5
x /= 4
print("Division can be obtained using /= characters = ",x)
x = 5
x %= 4
print("Modulus calculation is obtained using %= characters = ",x)
x = 5
x //= 4
print("Floor Division is obtained using //= characters = ",x)
x = 5
x **=4
print("Exponent calculation is obtained using **= characters = ",x)```

Running the script will result in the following output: ### Base2 calculation

The next set of snippets performs a bitwise calculation on a number; a bitwise operator is an operator used to perform bitwise operations on bit patterns or binary numerals involving the manipulation of individual bits. It operates on a bit string, a bit array or a binary numeral, considered a bit string, at the level of its bits. It is a fast and straightforward action, basic to the higher-level arithmetic operations and directly supported by the processor.

In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary, and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format1.

Python’s bitwise operators let you manipulate those individual bits of data at the most granular level. You can use bitwise operators to implement compression, encryption, and error detection algorithms.

Our first snippet below performs a bitwise AND operation between the values of “x” (currently equal to “5” in binary form as “101”) and “4” (equal to “100” in binary form). The result of this operation is “100”, which is equal to the decimal number “4”. The new value of “x” becomes “4” after this operation.

```x = 5
x &= 4
print(x)```

This code performs a bitwise “OR” operation between the values of “x” (currently equal to “5” in binary form as “101”) and “4” (equal to “100” in binary form). The result of this operation is “101”, which is equal to the decimal number “5”. The new value of x becomes “5” after this operation.

```x = 5
x |= 4
print(x)```

This code performs a bitwise “XOR” operation between the values of “x” (currently equal to “5” in binary form as “101”) and “4” (equal to “100” in binary form). The result of this operation is ‘001’, which is equal to the decimal number ‘1’. The new value of x becomes ‘1’ after this operation.

```x = 5
x ^= 4
print(x)```

The bitwise right shift operation shifts the bits of the left operand to the right by the number of positions specified by the right operand. In this case, “5” is “101” in binary. Shifting it to the right by “4” positions results in “000”, equal to “0” in decimal. The result of the operation is then assigned back to the “x” value.

```x = 5
x >>= 4
print(x)```

This code shifts the bits in “x” two places to left, effectively multiplying it by two raised to power two, which results in an output of “80”.

```x = 5
x <<= 4
print(x)```

Our written script is shown below:

```x = 5
x &= 4
print("This is a Bitwise AND operation = ",x)
x = 5
x |= 4
print("This is a Bitwise OR operation = ",x)
x = 5
x ^= 4
print("This is a Bitwise XOR operation = ",x)
x = 5
x >>= 4
print("This moves the bits 2 places to the right and = ", x)
x = 5
x <<=4
print("This moves the bits to places to the left and =  ",x)```

And the output is shown below: ## Comparison Operators

We now move on to Comparison Operators. Comparison operators are used to compare two values and return a boolean value (True or False) based on the comparison result. In Python we have six comparison operators; we have highlighted them in the table below:

 Operator Name Example == The result should be equal x == y != The result should not be equal x != y > The result should be greater than the input x > y < The result should be less then the input x < y >= The result should be greater than or equal to the input x >= y <= The result should be less than or equal to the input x <= y

We have also included some usage examples:

In this snippet, both “x” and “y” are equal to “5” there; the result of the comparison is “True” as we are using the “==”.

```x = 5
y = 5
print(x == y)```

In this snippet, “x” is equal to “5” and “y” is equal to “6”; therefore, the comparison result is not equal and satisfies the Comparison “x != y”, and the result is “True”.

```x = 5
y = 6
print(x != y)```

In this snippet, “x” is equal to “5” and “y” is equal to “6”; as we are using the greater than comparison “x” is not greater than “y”; therefore, the result is “False”.

```x = 5
y = 6
print(x > y)```

In this snippet, “x” is equal to “5” and “y” is equal to “6”; as we are using the less than comparison,  “x” is less than “y”; therefore, the result is “True”.

```x = 5
y = 6
print(x < y)```

In this snippet, “x” is equal to “5” and “y” is equal to “6”; as we are using the greater or equal to comparison, “x” is less than “y”; therefore, the result is “False”.

```x = 5
y = 6
print(x >= y)```

In this snippet, “x” is equal to “5” and “y” is equal to “6”; as we are using the less than or equal to comparison, “x” is less than “y”; therefore, the result is “True”.

```x = 5
y = 6
print(x <= y)```

our script is below:

```x = 5
y = 5
result1 = x == y
print("the result of 5==5 is equal, therefore the return is", result1)
x = 5
y = 6
result2 = x != y
print("The result of 5 != 6 is not equal, so the return is", result2)
x = 5
y = 6
result3 = x > y
print("The result of 5 > 6 is not greater then, so the result is", result3)
x = 5
y = 6
result4 = x < y
print("The result of 5 < 6 is less than, so the result is", result4)
x = 5
y = 6
result5 = x >= y
print("The result of 5 >= 5 is greater than or equal to, so the result is", result5)
x = 5
y = 6
result6 = x <= y
print("The result of 5 <= 6 is less than or equal to, so the result is", result6)```

The results are below: ### Python Logical Operators

In Python, logical operators combine two or more conditions and return a boolean value (True or False) based on the result of the combination. Python has three logical operators, these are:

• and: returns True if both conditions are True
• or: returns True if at least one condition is True
• not: returns the opposite of the condition (True if the condition is False, and vice versa)

As per usual, we have included some example snippets that use logical operators:

In our first snippet, the values of “x” is “5”, “y” is “10”, and “z” is “15”, and our two comparisons are “x” less than “y” and “z” greater than “y”. In this case, both sides of the condition are true; therefore, the result is “True”.

```x = 5
y = 10
z = 15
result1 = x < y and y < z
print(“As 5 is less than 10 and 15 is greater than 10 both conditions are”, result1)```

We have the same values in our second example, but the “or” operator will return “true” if both conditions are valid. Therefore, as “x” is not greater than “y” but “z” is greater than “y” the result is “True”.

```x = 5
y = 10
z = 15
result2 = x > y or y < z
print(“As 5 is not greater than 10, but 15 is not greater than 10, one condition is met, so the result is”, result2)```

Our final snippet tests the “NOT” operator; therefore, as “5” is not “10” the outcome is “True”

```x = 5
y = 10
result3 = not x > y
print(“As 5 is not 10 the condition is met, so the result is”,result3”)```

Our script is below:

```x = 5
y = 10
z = 15
result1 = x < y and y < z
print("As 5 is less than 10 and 15 is greater than 10 both conditions are", result1)
x = 5
y = 10
z = 15
result2 = x > y or y < z
print("As 5 is not greater than 10, but 15 is not greater than 10, one condition is met, so the result is", result2)
x = 5
y = 10
result3 = not  x > y
print("As 5 is not 10 the condition is met, so the result is",result3)```

Our output after running the script is shown below: ### Python Identity Operators

In Python, identity operators are used to compare the memory locations of two objects and return a boolean value (True or False) based on the comparison result. There are two identity operators in Python:

• is: returns True if both objects are the same object (have the same memory location)
• is not: returns True if both objects are not the same object (do not have the same memory location)

Here are some examples of Python scripts that use identity operators:

In our first snippet, we are validating the “is” statement; in line four, we check if “x is y” and as “x” is not the same as “y” the answer is “false”, however in line five, we check if ”x is z” and as “x” is indeed the same as “z”, the response is “true”.

```x = [1, 2, 3]
y = [4, 5, 6]
z = x
print(x is y)
print(x is z)```

we are validating the “is not” statement in the second snippet.  In line four, “x” is not the same as “y” our output is “true”.  In line five, we are validating if “x” is not the same as “z”, and as it is, the result is “false”.

```x = [1, 2, 3]
y = [4, 5, 6]
z = x
print(x is not y)
print(x is not z)```

Our script looks like this:

```x = [1, 2, 3]
y = [4, 5, 6]
z = x
result1 = x is y
result2 = x is z
print("As x is different to y the result of our is statement is" , result1)
print("As x is the same as z the result of our is statement is", result2)
x = [1, 2, 3]
y = [4, 5, 6]
z = x
result3 = x is not y
result4 = x is not z
print("As x is different to y the result of our is not statement is" , result1)
print("As x is the same as z the result of our is not statement is", result2)```

Output is shown below: ### Python Membership Operators

Python membership operators test whether a value is in a sequence (string, list, tuple, set and dictionary). The membership operators are “in” and “not in”.

Here is an example script, our variable inputs our list of 3 entities, “1, 2, 3”, our first statement in line two returns “True” as  the value “1” is in the our list, but the second statement in line three will return “false” as the value “4” is not in the list.

```x = [1, 2, 3]
print(1 in x)
print(4 not in x)```

This is our script:

```x = [1, 2, 3]
result1 = 1 in x
result2 = 4 in x
print("As 1 is in the list 1, 2, 3, the result is", result1)
print("As 4 not in the list 1, 2, 3, the result is",result2)```

the Script output is shown here: ## Summary

Sometimes an article is a sprint; sometimes, it is a marathon; this was the latter. But it is better to have all this information on operators on a single page.  In the next article we will look at string formatting.

00:02:26

00:02:39

00:07:14

00:07:53

00:04:30