1.2.1.4 PCEP-30-02 Practice Test Compendium โ€“ Operators

Operators

01) An operator is a symbol that determines an operation to perform. The operator along with its arguments (operands) forms an expression that is subject to evaluation and provides a result.

02) There are three basic groups of operators in Python:

  • arithmetic, whose arguments are numbers;

  • string, which operates on strings or strings and numbers;

  • Boolean, which expects that their arguments are Boolean values.

03) A unary operator is an operator with only one operand.

04) A binary operator is an operator with two operands.

Unary arithmetic operators

Operator
Meaning
Example

-

Change argument's sign

-(-2) is equal to 2

+

Preserve argument's sign

+(-2) is equal to -2

Binary arithmetic operators (ordered according to descending priority)

Priority
Operator
Name
Example
Meaning
Result
Result Type

Highest

**

Exponentiation

2 ** 3

232^3

8

  • int if both arguments are ints

  • float otherwise

*

Multiplication

2 * 3

2 ร— 3

6

  • int if both arguments are ints

  • float otherwise

/

Division

4 / 2

4 รท 2

2.0

  • always float

  • raises ZeroDivisionError when divider is zero

//

Integer division

5 // 2

2

  • int if both arguments are ints

  • float otherwise

  • raises ZeroDivisionError when divider is zero

%

Remainder (modulo)

5 % 2

5 mod 2

1

  • int if both arguments are ints

  • float otherwise

  • raises ZeroDivisionError when divider is zero

Lowest

+

Addition

2 + 1

2 + 1

3

  • int if both arguments are ints

  • float otherwise

-

Subtraction

2 - 1

2 โˆ’ 1

1

  • int if both arguments are ints

  • float otherwise

pairs of parentheses can be used to change the order of operations, for example:

  • 2 + 3 * 4 evaluates to 24

  • (2 + 3) * 4 evaluates to 20

when operators of the same priority (other than **) are placed side-by-side in the same expression, they are evaluated from left to right: therefore, the expression:

1 / 2 * 2

evaluates to 1.0, not to 0.25.

This convention is called left-sided binding.

when more than one ** operator is placed side-by-side in the same expression, they are evaluated from right to left: therefore, the expression:

2 ** 2 ** 3

evaluates to 256 (282^8), not to 64 (434^3) โ€“ this is right-sided binding.

Last updated