PCEP 2.3 (E1M2) – Python Operators: Summary
2.3.1.1 – Python as a Calculator
Python’s print() can evaluate expressions, like print(2 + 3) outputs 5.
Python can function as a simple calculator.
Operators are symbols that operate on values to form expressions.
Basic arithmetic operators: +, -, *, /, //, %, **.
2.3.1.2 – Exponentiation Operator **
** raises a number to a power (e.g., 2 ** 3 = 8).
Type rules:
int ** int → int
If any operand is float, result is float.
2.3.1.3 – Multiplication * and Division /
is standard multiplication. Follows type rules like exponentiation.
/ always returns a float, even if inputs and result are whole numbers.
2.3.1.4 – Integer (Floor) Division //
// returns the integer result (rounded down) of a division.
-6 // 4 = -2 → always rounds towards the lower integer.
Follows type rules: int // int → int; with float, result → float.
2.3.1.5 – Modulo Operator %
% returns the remainder after integer division.
Follows float rules too (e.g., 12 % 4.5 = 3.0).
Rule: a % b = a - (b * (a // b))
Division by 0 using /, //, or % raises an error.
2.3.1.6 – Addition + and Subtraction -
adds values; - subtracts.
Operators can be binary (4 - 2) or unary (-4).
Unary + is valid but usually unnecessary (+2 returns 2).
2.3.1.7 – Operator Priority (PEMDAS)
Operator precedence:
1. Parentheses ()
2. Exponentiation **
3. *, /, //, %
4. +, -
Example: 2 + 3 * 5 → 2 + 15 = 17
2.3.1.8 – Operator Binding Direction
Left-sided binding: most operators, like %, evaluate left to right (e.g., 9 % 6 % 2 = 1).
Right-sided binding: ** evaluates right to left (e.g., 2 ** 2 ** 3 = 256).
2.3.1.9 – Simplified Operator Priority Table
1: ** (Exponentiation)
2: Unary +, - (e.g., -5)
3: *, /, //, %
4: Binary +, -
Unary operators next to ** bind stronger.
Example: -2 ** 2 = -4; 2 ** -2 = 0.25
Same priority operators: evaluated left to right.
2.3.1.10 – Section Summary
1. Expressions evaluate to values.
2. Operators perform actions on values.
3. Arithmetic operators: +, -, *, /, %, **, //
4. Unary operators: +3, -2; Binary: 4 + 5
5. Precedence: ** , unary +,- , *,/,//,% , binary +,-
6. Parentheses alter evaluation order.
7. Exponentiation (**) binds right-to-left.
Exercise Results
print((2 * 4), (2 ** 4), (2 * 4.)) → 8 16 8.0
print((-2 / 4), (2 / 4), (2 // 4), (-2 // 4)) → -0.5 0.5 0 -1
print((2 % -4), (2 % 4), (2 ** 3 ** 2)) → -2 2 512
Extra:
2 % -4 = -2
-2 % 4 = 2
-2 % -4 = -2
Rule: a % b = a - (b * floor(a / b))
Python in Tamil. Learn Python in Tamil from Govi. YouTube Channel: @Python_In_Tamil.
Информация по комментариям в разработке