Operations- Data Manipulation Tools

Simple Operations

Python has the capability of carrying out calculations. Enter a calculation directly into the print statement: print(2 + 2) Answer = 4 print(5 + 4 - 3) Answer = 6 The spaces around the plus and minus signs here are optional (the code would work without them), but they make it easier to read.

Python also carries out multiplication and division, using an asterisk * to indicate multiplication and a forward slash / to indicate division. Use parentheses to determine which operations are performed first. print (2*(3+4)) Answer = 14 print (10/2) Answer = 5.0

Using a single slash to divide numbers produces a decimal (or float, as it is called in programming)

The order of their appearance is not accidental. We'll talk more about it once we've gone through them all.

Exponentiation (**)

A double asterisk ** sign is an exponentiation operator

print( 2**5 ) print( 9 ** (1/2) )

You can chain exponentiations together. In other words, you can rise a number to multiple powers. For example 2**3**2

Quotient (//)

Floor division is done using two forward // slashes and is used to determine the quotient of a division (the quantity produced by the division of two numbers). For example: print( 20 // 6 ) Ans = 3 [6 goes into 20 three times] remainder 2 but we check if the remainder is 2, rounded off to the LESSER integer, so the answer remain a= 3 You can also use floor division on floats.

Remainder (%)

The modulo operator is carried out with a percent symbol (%) and is used to get the remainder of a division. For example:

print(20 % 6) Ans = 2 20 // 6 = 3 3*6 = 18 20-18=2

print(1.25 % 0.5) Ans = 0.25 1.25 // 0.5 = 2.0 2.0 * 0.5 = 1.0 1.25 -1 = 0.25

print(12 % 4.5) Ans = 3.0 12 // 4.5 = 2.0 2 * 4.5 =9.0 12 - 9.0 = 3.0

Remember integer divided by a float is always a float !!

Operators and their Binding

Don't forget PEMDAS(Parentheses, Exponents, Multiplication and Division[left to right], Addition and Subtraction[left to right]) when it comes to figuring which to do first :)

The binding of the operator determines the order or computations performed by some operators with equal priority, put side by side in one expression. Most of Pythons options have left-sided binding, which means that the calculation of expressions is handled from left to right. For example: print (9 % 6 % 2)

As can be seen, this occurs by Python using the left-sided binding - But there is one interesting exception!! - EXPONENTIATION

Exponentiation - Use Right-Sided Binding

print (2 ** 2 ** 3)

2**3 = 8 2**8 = 256

Operators and Parentheses

print((5 * ((25 % 13) + 100) / (2 * 13)) // 2) print[((5 * ((25 % 13) + 100) / 26] 25 // 13 = 1 1 * 13 = 13 25 - 13 = 12 12 + 100 = 112 112 * 5 = 560 --------------- 560 / 26 = 21.53 21.53 // 2 Answer = 10.0

List of Priorities

Learnt Lists of Priorities so far: -

Last updated

Was this helpful?