Python From Beginner to Advanced

0% completed

Previous
Next
Python - Operators

Introduction to Python Operators

Operators in Python are special symbols that perform operations on one or more operands. Operands are the values or variables with which these operators are applied to produce a result. Operators are the building blocks of Python expressions and are essential for performing calculations, making decisions, manipulating data, and more. Python supports a wide range of operators, each serving different purposes:

Image
  • Arithmetic Operators: Perform basic mathematical operations.
  • Comparison (Relational) Operators: Compare two values and determine their relationship.
  • Assignment Operators: Assign values to variables.
  • Logical Operators: Combine conditional statements.
  • Bitwise Operators: Perform bitwise calculations on integers.
  • Membership Operators: Test membership in sequences such as lists or strings.
  • Identity Operators: Compare the memory locations of two objects.

In this lesson, we will explore each type of operator, providing definitions, usage examples, and detailed explanations of how they work in Python. This foundational knowledge will help you write more efficient and effective Python code.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and more between numbers.

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
**Exponentiationa ** b
//Floor divisiona // b

Example

Python3
Python3

. . . .

Explanation:

  • a + b adds 10 and 3, giving the result 13.
  • a - b calculates the difference between 10 and 3, resulting in 7.
  • a * b performs multiplication between 10 and 3, resulting in 30.
  • a / b divides 10 by 3, providing a floating point result of approximately 3.333.
  • a % b computes the modulus, which is the remainder when 10 is divided by 3, resulting in 1.
  • a ** b calculates the exponentiation, raising 10 to the power of 3 to get 1000.
  • a // b performs floor division, dividing 10 by 3 and rounding down to the nearest whole number, 3.

Comparison (Relational) Operators

Comparison operators are used to compare two values, outputting a Boolean value based on whether the comparison is true or false.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

Example

Python3
Python3

. . . .

Explanation:

  • a == b tests if 10 is equal to 3, which is false.
  • a != b tests if 10 is not equal to 3, which is true.
  • a > b checks if 10 is greater than 3, which is true.
  • a < b checks if 10 is less than 3, which is false.
  • a >= b checks if 10 is greater than or equal to 3, which is true.
  • a <= b checks if 10 is less than or equal to 3, which is false.

Assignment Operators

Assignment operators in Python are used to assign values to variables, often simplifying code by combining standard operations with an assignment.

OperatorDescriptionExample
=Simple assignmenta = b
+=Addition and assignmenta += b
-=Subtraction and assignmenta -= b
*=Multiplication and assignmenta *= b
/=Division and assignmenta /= b
%=Modulus and assignmenta %= b
**=Exponent and assignmenta **= b
//=Floor division and assignmenta //= b
&=Bitwise AND and assignmenta &= b
|=Bitwise OR and assignment`a
^=Bitwise XOR and assignmenta ^= b
<<=Left shift and assignmenta <<= b
>>=Right shift and assignmenta >>= b

Example

Python3
Python3

. . . .

Explanation:

  • a += 3 adds 3 to a, updating a to 13.
  • a -= 2 subtracts 2 from a, updating a to 11.
  • a *= 2 multiplies a by 2, updating a to 22.
  • a /= 2 divides a by 2, updating a to 11.0 (division converts to float).
  • a %= 4 computes the modulus of a divided by 4, updating a to 3.0.
  • a **= 2 raises a to the power of 2, updating a to 9.0.
  • a //= 2 performs floor division of a by 2, updating a to 4.0.
  • a &= 3 performs a bitwise AND with 3, updating a to 0 (since 4 & 3 results in 000).
  • a |= 8 performs a bitwise OR with 8, updating a to 8 (since 000 | 1000 results in 1000).
  • a ^= 6 performs a bitwise XOR with 6, updating a to 14 (since 1000 ^ 0110 results in 1110).
  • a <<= 1 shifts a left by 1 bit, updating a to 28 (doubling the value).
  • a >>= 2 shifts a right by 2 bits, updating a to 7 (effectively dividing by 4 and truncating towards zero).

Logical Operators

Logical operators are used to combine conditional statements in Python. They are fundamental in expressing compound conditions.

OperatorDescriptionExample
andLogical ANDa and b
orLogical ORa or b
notLogical NOTnot a

Example

Python3
Python3

. . . .

Explanation:

  • a and b evaluates to False because with and, both operands must be true, but b is False.
  • a or b evaluates to True because with or, only one operand needs to be true.
  • not a simply negates a, turning True into False.

Bitwise Operators

Bitwise operators are used to perform bit-level operations on integers. They manipulate individual bits of these numbers.

OperatorDescriptionExample
&Bitwise ANDa & b
|Bitwise ORa | b
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left Shifta << b
>>Right Shifta >> b

Example

Python3
Python3

. . . .

Explanation:

  • a & b performs a bitwise AND, which results in 2 because the second bit is set in both a and b.
  • a | b performs a

bitwise OR, resulting in 3 because at least one of the corresponding bits is set.

  • a ^ b performs a bitwise XOR, resulting in 1 because only one of the corresponding bits is set in either a or b.
  • ~a is the bitwise NOT operation, which inverts all bits of a, leading to -3 (due to two's complement representation).
  • a << 1 shifts all bits in a left by one position, doubling the number to 4.
  • a >> 1 shifts all bits in a right by one position, halving the number to 1.

Membership Operators

Membership operators in Python are used to test whether a value or variable is found in a sequence (string, list, tuple, etc.).

OperatorDescriptionExample
inTrue if value is in sequencex in y
not inTrue if value is not in sequencex not in y

Example

Python3
Python3

. . . .

Explanation:

  • 3 in list checks if 3 is a member of the list [1, 2, 3, 4, 5], which is true.
  • 6 not in list checks if 6 is not a member of the list, which is true since 6 is absent.

Identity Operators

Identity operators compare the memory locations of two objects. They are used to check if objects are actually the same instance, beyond just having equal value.

OperatorDescriptionExample
isTrue if both sides are the same objecta is b
is notTrue if sides are different objectsa is not b

Example

Python3
Python3

. . . .

Explanation:

  • a is b checks if a and b refer to the same object, which is false because they are equal but not the same object.
  • a is c confirms that a and c refer to the same object, which is true since c is assigned to a.
  • a is not b checks if a and b are not the same object, which is true as they are different instances.

Python Operator Precedence

Operator precedence in Python determines the order in which operations are processed. This can affect the outcome of expressions where multiple operators appear. Higher precedence operators are executed before lower precedence ones.

Here's a simplified list of Python operator precedence, from highest to lowest:

PrecedenceOperator TypeOperators
1Parentheses()
2Exponentiation**
3Unary plus, Unary minus, Bitwise NOT+x, -x, ~x
4Multiplicative*, /, %, //
5Additive+, -
6Bitwise shifts<<, >>
7Bitwise AND, OR, XOR&, |, ^
8Comparison==, !=, >, <, >=, <=
9Equalityis, is not
10Membershipin, not in
11Logical NOTnot
12Logical ANDand
13Logical ORor

Example

Python3
Python3

. . . .

Explanation:

  • This example evaluates using Python's operator precedence rules:
    • c ** 2 is calculated first because ** has the highest precedence among the operators used, resulting in 900.
    • b * 900 is next, producing 18000.
    • 18000 / 10 is calculated, yielding 1800.
    • a + 1800 gives 1810.
    • 1810 - 5 results in 1805.
    • 1805 <= b is evaluated (False since 1805 is not less than or equal to 20).
    • b % a == 0 checks if 20 is divisible by 10 without remainder (True).
    • c > b is True since 30 is greater than 20.
    • True and True is True.
    • False or True results in True.
  • The result variable is True because the logical OR operation returns True if at least one of its operands is True.

Understanding operator precedence is essential for writing clear and correct Python code, especially in complex expressions. It ensures that you can predict and control the order of operations without excessive use of parentheses.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next